go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (context cancellation not propagated)

ID: go/goroutine-context-cancel-not-propagated

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-02-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

A parent goroutine cancels a context but child goroutines are not listening to the context's Done channel, causing them to block indefinitely.

generic

中文

父协程取消上下文,但子协程未监听上下文的 Done 通道,导致它们无限阻塞。

Workarounds

  1. 95% success Use select to listen on context.Done() in blocking operations.
    select {
    case result := <-ch:
        return result
    case <-ctx.Done():
        return ctx.Err()
    }
  2. 90% success Pass context to functions and check cancellation periodically.
    func worker(ctx context.Context) error {
        for {
            select {
            case <-ctx.Done():
                return ctx.Err()
            default:
                // do work
            }
        }
    }

Dead Ends

Common approaches that don't work:

  1. Only checking context.Err() without using select on Done. 80% fail

    context.Err() is only set after cancellation; without select, goroutine may not wake up.

  2. Passing context by value but not using it in select. 70% fail

    The context is available but not used to unblock the goroutine.