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
+21.7k Golang : simulate tail -f or read last line from log file example
+18.5k Golang : How to Set or Add Header http.ResponseWriter?
+15.8k Golang : Set up source IP address before making HTTP request
+10.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+9.6k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+11k Golang : Perform sanity checks on filename example
+14.6k Golang : Get checkbox or extract multipart form data value example
+8.2k Golang : Intercept and compare HTTP response code example
+17.3k Golang : Get download file size
+11k Golang : Clean formatting/indenting or pretty print JSON result
+7.6k PHP : How to parse ElasticSearch JSON ?
+10.8k Golang : Handle API query by curl with Gorilla Queries example