Sobes.tech
Senior

How to handle context cancel so that all workers immediately stop when the context is canceled? How to use select to read from a channel considering the context?

sobes.tech AI

Answer from AI

To immediately stop all workers when cancelling the context in Go, each worker should listen for the cancellation signal via the ctx.Done() channel. Using select allows waiting for data from the worker channel and the cancellation signal simultaneously.

Example:

func worker(ctx context.Context, jobs <-chan Job) {
    for {
        select {
        case <-ctx.Done():
            // Context is cancelled — stop working
            return
        case job, ok := <-jobs:
            if !ok {
                // Channel is closed — stop working
                return
            }
            // Process job
            process(job)
        }
    }
}

// In the main code, create a cancellable context
ctx, cancel := context.WithCancel(context.Background())
// Launch workers
for i := 0; i < numWorkers; i++ {
    go worker(ctx, jobs)
}

// When cancellation is needed, call cancel()
cancel()

This approach guarantees that when cancel() is called, all workers immediately receive the signal and stop working without delays.

How to handle context cancel so that all workers… - sobes.tech