Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When main exits, do goroutines run defer()? [duplicate]

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?

like image 611
Dallin M. Avatar asked Oct 28 '25 02:10

Dallin M.


1 Answers

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.

like image 55
Zazeil Avatar answered Oct 30 '25 20:10

Zazeil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!