go runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-08-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. Adding a default case to select 70% fail

    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% fail

    If channel becomes nil dynamically, race condition may occur.