Home >Backend Development >Golang >How to Gracefully Terminate a Goroutine in Go?
Killing a Goroutine Gracefully
In Go, goroutines provide concurrency, allowing multiple tasks to execute simultaneously. Sometimes, it becomes necessary to terminate a goroutine, such as when we need to gracefully shut down an application.
Consider the following code:
<code class="go">func startsMain() { go main() } func stopMain() { //kill main } func main() { //infinite loop }</code>
In this scenario, the main goroutine runs an infinite loop, and we wish to stop it in the stopMain function. How can we achieve this?
The solution lies in using channels to communicate between goroutines. Here's an improved code snippet:
<code class="go">var quit chan struct{} func startLoop() { quit = make(chan struct{}) go loop() } func stopLoop() { close(quit) } // BTW, you cannot call your function main, it is reserved func loop() { for { select { case <-quit: return // better than break default: // do stuff. I'd call a function, for clarity: do_stuff() } } }</code>
We introduce a quit channel of type struct{}, which can hold an empty struct value.
This mechanism allows us to gracefully terminate the infinite loop by signaling the goroutine through the quit channel.
The above is the detailed content of How to Gracefully Terminate a Goroutine in Go?. For more information, please follow other related articles on the PHP Chinese website!