Looking through some examples of worker pools in Go, I couldn't identify a consistent approach to closing channels. For example, this project on Github seems to close all channels, while this similar implementation does not once close a channel! I know that closing a channel indicates completion; no more values can be sent on it. But is it just a runtime assertion? Don't open channels also leave behind memory leaks? Or do you just rely on garbage collection? And where would I close the channels opened in the second example if I were to do it explicitly?
Asked
Active
Viewed 216 times
0
-
2"Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop." https://tour.golang.org/concurrency/4 – Peter Feb 25 '20 at 12:19
-
Thank you! It would still be interesting to know how to close the channels in the second example. Especially how to properly close the nested channels in `readyPool`. – vgn74509 Feb 25 '20 at 12:23
1 Answers
0
Channels can be used any way you like:
- If you are sending a finite number of items, closing the channel indicates to the listener no more items are coming
- if you implementing a continuous stream (micro-service etc) the channel will never be closed.
- a channels close event can be used to signal an event
Note: You do not have to close a channel for it to be garbage collected. Once the channel goes out of scope on the producer & consumer sides, it will be reclaimed, even if there are unread items on the channel.

colm.anseo
- 19,337
- 4
- 43
- 52
-
Thanks for the quick response! I conclude that closing the channels in the Github project I linked just helps with the cleanup in case the user forgets to dereference the whole pool after stopping it (because it can be started only once). – vgn74509 Feb 25 '20 at 12:41