"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Gracefully Terminate a Running Goroutine in Go?

How to Gracefully Terminate a Running Goroutine in Go?

Published on 2024-11-04
Browse:535

How to Gracefully Terminate a Running Goroutine in Go?

Signaling Goroutines to Terminate

In Go, handling goroutine termination can be crucial when ensuring graceful application shutdown or managing resource allocation. This article explores a technique to signal a running goroutine to stop its execution.

The example provided in the inquiry demonstrates a goroutine that infinite loops, simulating continuous processing. The goal is to terminate this goroutine if it exceeds a specified timeout.

An initial approach involves using two channels: one for communication, and the other for signaling termination. However, reading from the signaling channel would block the goroutine, defeating its intended purpose.

Using an Additional Stop Channel

One effective solution is to introduce an additional stop channel, tooLate, of type chan struct{}. Inside the goroutine, a select statement is used to monitor both the communication channel and the stop channel. If the tooLate channel receives a value, the goroutine gracefully returns, terminating its processing loop.

Here's the modified code snippet:

func main() {
    // tooLate channel to signal goroutine to stop
    tooLate := make(chan struct{})
    proCh := make(chan string)

    go func() {
        for {
            fmt.Println("working")
            time.Sleep(1 * time.Second)

            select {
            case 

In this solution, the proCh channel continues to be used for communication, while the tooLate channel serves as the signal for termination. When the tooLate channel is closed, the goroutine detects this and exits its loop.

Other Considerations

Besides using an additional channel, there are alternative approaches for signaling goroutines, such as using the built-in sync.Cond type for more fine-grained control over goroutine synchronization. The choice of technique depends on the specific requirements of your application.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3