Sobes.tech
Junior — Middle

How can you correctly stop a running goroutine if it needs to terminate based on an external signal or condition, even if the result has not yet been received?

sobes.tech AI

Answer from AI

To properly stop a running goroutine in Go based on an external signal or condition, the common approach is to use a context.Context or channels to transmit a cancellation signal.

Example using context:

func worker(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            // Cancellation signal received, ending goroutine
            return
        default:
            // Perform work
        }
    }
}

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

    // At some point, call cancel() to stop the goroutine
    cancel()
}

This approach allows the goroutine to regularly check if a stop signal has been sent and terminate gracefully, even if the result has not yet been received. Similarly, a channel can be used to transmit a stop signal, but context is a more idiomatic and convenient method in Go.

How can you correctly stop a running goroutine if it… - sobes.tech