If a process is killed by the kernel for some reason (or kill
-9) none of these cleanup functions will run. The last will
idea is meaningful only when the main() dies and doesn't care
to wait for all the other goroutines to die a clean death.
But in this case you are in essence passing a function (that
needs the context of one thread) to another thread (main).
This can't work and even if you make it work somehow,
debugging it would be a nightmare.
Just as a defer is cleanups to be run when a function exits
and C's atexit() is cleanups to be run when a process exits,
cleanups to be run when a goroutine exits is meaningful and
can be run in the same context as the goroutine. Such
cleanups can be used in normal code as well.
Implementation idea: the runtime must have something that
uniquely identifies a goroutine. This "id" can be used as a
key to store a chain of cleanup functions. Exiting a thread
would run any such functions.
You don't need the equivalent of C's atexit() function since
on process exist (via main() terminating or OS.Exit()), the
runtime finds all alive threads and cause them to run any
cleanups before destroying them. Not having looked at the
runtime I am not sure how painful this is but this has the
benefit of not adding any cost when there is no goroutine
level cleanup.
As for syntax I am tempted to suggest "go defer"!
> To unsubscribe from this group and stop receiving emails from it, send an email to
golang-nuts...@googlegroups.com.
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
golang-nuts...@googlegroups.com.