go runtime_error ai_generated true

致命错误:所有 goroutine 都处于休眠状态 - 死锁!(在 nil 通道上 select)

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

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

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

版本兼容性

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

根因分析

包含 nil 通道的 select 语句会永远阻塞,因为对 nil 通道的发送/接收会无限期阻塞。

English

A select statement with a nil channel case blocks forever because sending/receiving on nil channel blocks indefinitely.

generic

解决方案

  1. 95% 成功率 Initialize channels before using in select
    ch := make(chan int)
    select {
    case <-ch:
        // handle
    case <-time.After(time.Second):
        // timeout
    }
  2. 85% 成功率 Use a non-nil placeholder channel if channel may be nil
    if ch == nil { ch = make(chan int) } // but ensure it's used properly

无效尝试

常见但无效的做法:

  1. Adding a default case to select 70% 失败

    Default case runs if all channels are nil, but if only some are nil, it may still block.

  2. Checking channel for nil before select 80% 失败

    If channel becomes nil dynamically, race condition may occur.