go runtime_error ai_generated true

fatal error: 所有 goroutine 都处于休眠状态 - 死锁!(nil channel 发送)

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

ID: go/channel-send-to-nil-channel

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

版本兼容性

版本状态引入弃用备注
1.0+ active

根因分析

某个 goroutine 尝试向 nil channel 发送数据,这会永久阻塞。如果没有其他 goroutine 可以继续执行,运行时会检测到死锁。

English

A goroutine attempted to send to a nil channel, which blocks forever. If no other goroutine can proceed, the runtime detects a deadlock.

generic

解决方案

  1. 98% 成功率
    ch := make(chan int)
    // or ch := make(chan int, 1)
  2. 90% 成功率
    select {
    case ch <- v:
    case <-time.After(1 * time.Second):
        return errors.New("timeout: channel may be nil")
    }

无效尝试

常见但无效的做法:

  1. 90% 失败

    A nil channel in a select will never be ready, so the default case will always be taken, silently dropping the send.

  2. 85% 失败

    Checking for nil is not atomic and does not guarantee the channel is initialized; it may still be nil at send time.