go runtime_error ai_generated true

致命错误:所有 goroutine 都休眠——死锁(在 nil channel 上接收)

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

ID: go/receive-on-nil-channel-blocks

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

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.21 active — — —
1.22 active — — —

根因分析

从 nil channel 接收会永久阻塞。若 channel 变量从未被赋值却用于 select 或接收,goroutine 将永久挂起。

English

A receive from a nil channel blocks forever. If the channel variable was never assigned and is used in a select or receive, the goroutine hangs permanently.

generic

解决方案

  1. 92% 成功率
    ch := make(chan int)
    go func() { ch <- 1 }()
    v := <-ch
    fmt.Println(v)
  2. 85% 成功率
    select {
    case v := <-ch:
        fmt.Println(v)
    case <-ctx.Done():
        return ctx.Err()
    }

无效尝试

常见但无效的做法:

  1. 50% 失败

    It prevents the hang but the underlying nil channel is still never populated, so the program silently times out instead of working.

  2. 70% 失败

    The default case fires immediately forever, spinning in a busy loop consuming CPU.