Golang : How to flush a channel before the end of program?
Problem :
Your program that uses channels and go routines did not print out all the expected result. Upon investigation, it seems that the data in channels were not flushed out before the program termination. What can be done to flush data from channel before program termination?
Solution :
There is no build in method to "flush" data out from channel. You can either use WaitGroup to pause the program termination until all channels data are printed out or program your function to indicate if they are done (i.e goroutine completed ) before moving on to next process or terminate the program.
See examples at :
https://www.socketloop.com/tutorials/golang-wait-and-sync-waitgroup-example
https://www.socketloop.com/tutorials/golang-close-channel-after-ticker-stopped-example
See also : Golang : Close channel after ticker stopped example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.9k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+25.7k Golang : Daemonizing a simple web server process example
+5.5k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+31.4k Golang : bufio.NewReader.ReadLine to read file line by line
+19.3k Golang : How to count the number of repeated characters in a string?
+9.7k Random number generation with crypto/rand in Go
+8k Golang : Variadic function arguments sanity check example
+23.4k Golang : Get ASCII code from a key press(cross-platform) example
+14.8k Golang : Submit web forms without browser by http.PostForm example
+8.8k Golang : Sort lines of text example
+24k Golang : Find biggest/largest number in array
+26.8k Golang : Force your program to run with root permissions