gochannelgoroutinedefer-keyword

When main exits, do goroutines run defer()?


If I have a goroutine, can I close a channel I have open on that goroutine using something like this?

defer(close())

Or are defer statements not run for goroutines when main exits?


Solution

  • Nope, you can't. Once main done, the whole program is terminated. So you have to manually synchronize graceful termination, if you do need one. There are neat patterns, but that's another story.

    And yet it seems that you don't need closing at all. It is fine to keep chanels open, they are totally managed resources and will eventually be garbage-collected. Closing is more a design/intention act rather then a necessary cleanup.

    P.S. If you defer something() at the main's level, then indeed something will get executed after main returned. You may rely on this behavior.