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
+7.6k Golang : Grayscale Image
+8.5k Golang : How to capture return values from goroutines?
+24k Golang : GORM read from database example
+7.7k How to show different content from website server when AdBlock is detected?
+5.5k Golang : List all packages and search for certain package
+23.4k Golang : Upload to S3 with official aws-sdk-go package
+16.3k Golang : Set up source IP address before making HTTP request
+6.3k Golang : Find the longest line of text example
+6.4k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+23k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+5k Golang : If else example and common mistake
+33.3k Golang : Create x509 certificate, private and public keys