go runtime_error ai_generated true

致命错误:所有协程都在休眠 - 死锁!(上下文取消未传播)

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2025-02-20首次发现

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率 Use select to listen on context.Done() in blocking operations.
    select {
    case result := <-ch:
        return result
    case <-ctx.Done():
        return ctx.Err()
    }
  2. 90% 成功率 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
            }
        }
    }

无效尝试

常见但无效的做法:

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

    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% 失败

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