Home >Backend Development >Golang >How to Gracefully Terminate a Goroutine in Go?

How to Gracefully Terminate a Goroutine in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 17:22:02647browse

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.

  • In startLoop, we initialize the quit channel and launch the loop goroutine.
  • In stopLoop, we close the quit channel, signaling to the loop goroutine to stop.
  • In the loop goroutine, we use select with a default case to continuously check for signals from the quit channel. When a signal is received, the loop exits gracefully.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn