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
+32.4k Golang : Call a function after some delay(time.Sleep and Tick)
+27.7k Golang : Save map/struct to JSON or XML file
+8.4k Golang : Copy map(hash table) example
+5.1k Golang : Create new color from command line parameters
+12.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+5.7k Fix sudo yum hang problem with no output or error messages
+12.3k Golang : Query string with space symbol %20 in between
+31.7k Golang : Converting a negative number to positive number
+3.7k JavaScript: Add marker function on Google Map
+6.1k Golang : Gorrila mux.Vars() function example
+6.1k Nginx : How to block user agent ?
+16k Golang : How to remove certain lines from a file