I need to use defer
to free allocations manually created using C
library, but I also need to os.Exit
with non 0 status at some point. The
runtime.Goexit() is the easy way to accomplish that.
Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not panic, however, any recover calls in those deferred functions will return nil.
However:
Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.
So if you call it from the main goroutine, at the top of main
you need to add
defer os.Exit(0)
Below that you might want to add some other defer
statements that inform the other goroutines to stop and clean up.