Sobes.tech
Junior — Middle

How can you correctly stop goroutines using context in Go?

sobes.tech AI

Answer from AI

To properly stop goroutines in Go, the context package is often used. A cancelable context (context.WithCancel) is created and passed to the goroutine. Inside the goroutine, the context's state is periodically checked via <-ctx.Done(). When the cancel function is called, the Done() channel is closed, allowing the goroutine to terminate correctly.

Example:

func worker(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Goroutine stopped")
            return
        default:
            // perform work
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go worker(ctx)

    // after some time, stop the goroutine
    time.Sleep(time.Second)
    cancel()
    time.Sleep(time.Millisecond * 100) // to allow the goroutine to finish
}

This approach allows safe and controlled termination of goroutines without using unsafe methods.