go runtime_error ai_generated true

致命错误:所有协程都处于休眠状态 - 死锁!(从 nil 通道接收)

fatal error: all goroutines are asleep - deadlock! (receive from nil channel)

ID: go/goroutine-channel-receive-from-nil

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

版本兼容性

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

根因分析

协程尝试从 nil 通道接收数据,这会导致无限阻塞,如果没有其他协程可以解除阻塞,则会导致死锁。

English

A goroutine attempts to receive from a nil channel, which blocks indefinitely, causing a deadlock if no other goroutine can unblock it.

generic

解决方案

  1. 100% 成功率 Ensure channel is initialized before use
    ch := make(chan int)
    // use ch
  2. 90% 成功率 Use a default case in select to avoid blocking
    select {
    case val := <-ch:
        // process
    case <-time.After(1 * time.Second):
        // timeout
    }

无效尝试

常见但无效的做法:

  1. Initialize channel in init() 60% 失败

    If the channel is used before init() runs, it remains nil.

  2. Ignore the nil channel and add a timeout 80% 失败

    Timeout doesn't fix the root cause; the channel is still nil and will block again.