Home >Backend Development >Golang >What Happens to Unfinished Goroutines When Their Parent Goroutine Exits?
When the main or parent goroutine exits in a Go program, unfinished goroutines face an abrupt end. The entire runtime system shuts down, leaving no room for them to continue running, wait, or cancel. This phenomenon can be likened to flash paper igniting and disappearing instantly.
In the given code snippet from the Go programming book, upon the return of mirroredQuery, if the main goroutine exits, the two slow goroutines will cease to exist instantly, regardless of their current state. This can be considered a goroutine leak, but since the entire process terminates, the resources allocated are automatically cleaned up.
However, if the main goroutine is still running after mirroredQuery returns, the unfinished goroutines will continue to run until they:
In this case, they will send their responses to the channel and then return. Once all goroutines have returned, the channel will hold the responses as a minor resource leak. But as there are no remaining references to the channel, it will eventually be garbage-collected along with the strings it contains.
Using a buffered channel in this situation ensures that the goroutines do not block and continue running until they can complete their tasks. In the case of an unbuffered channel, the losing goroutines would block, causing the channel and its resources to remain allocated indefinitely.
The above is the detailed content of What Happens to Unfinished Goroutines When Their Parent Goroutine Exits?. For more information, please follow other related articles on the PHP Chinese website!