liveBook · Manning

Context.Done

As explained in 100 Go Mistakes and How to Avoid Them

The Done method returns a channel that is closed when a context's cancellation or deadline signal occurs.

A common mistake is treating Done as a channel that receives a cancellation value. Context.Done returns a receive-only notification channel that is closed when cancellation or a deadline occurs. Channel closure notifies every consumer, so multiple goroutines can observe the same signal. section 8.6.4

Use select to make channel operations context-aware. A send or receive performed directly can block after cancellation; competing with ctx.Done lets the function stop instead of waiting indefinitely. Return ctx.Err() to distinguish cancellation from an expired deadline. section 8.6.4

func handler(ctx context.Context, ch chan Message) error {
    for {
        select {
        case msg := <-ch:               #1
            // Do something with msg
        case <-ctx.Done():              #2
            return ctx.Err()
        }
    }
}

This handler keeps receiving messages until a message arrives or the context’s Done channel closes, then returns the cancellation reason. section 8.6.4

Protect each potentially blocking channel operation:

  • Guard a send with select so cancellation can interrupt the operation. section 8.6.4
  • Guard a receive with select for the same reason, returning ctx.Err() when Done closes. section 8.6.4
func f(ctx context.Context) error {
    // ...
    select {              #1
    case <-ctx.Done():
        return ctx.Err()
    case ch1 <- struct{}{}:
    }
 
    select {              #2
    case <-ctx.Done():
        return ctx.Err()
    case v := <-ch2:
        // ...
    }
}

The corrected function separately selects between context cancellation and completion of its send and receive operations. section 8.6.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains channel closure, cancellation errors, deadline errors, and select-based protection for blocking sends and receives.
Examples
Uses a message-receiving loop plus separate cancellation-aware send and receive operations.
What it assumes
Assumes familiarity with Go channels and functions receiving context.Context, while explaining cancellation signaling from the beginning.
What you can do after
Apply it via Go select statements to make channel operations respond to cancellation and deadlines.
How it connects
Connects context cancellation and deadlines with channels, select, blocking operations, and Err.

Also explained in

Compare how 2 books explain Context.Done →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.