go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (select with nil channels)

ID: go/select-on-nil-channels

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.1 active

Root Cause

A select statement with multiple cases where all channels are nil. In Go, a select with all nil channels blocks forever because no case can proceed.

generic

中文

一个选择语句有多个 case,但所有通道都是 nil。在 Go 中,所有通道都是 nil 的选择会永远阻塞,因为没有 case 可以执行。

Workarounds

  1. 95% success Ensure all channels in select are non-nil
    ch1 := make(chan int)
    ch2 := make(chan int)
    select {
    case <-ch1:
    case <-ch2:
    }
  2. 90% success Use a helper function to filter out nil channels
    func nonNilChannels(chs ...chan int) []chan int {
        var result []chan int
        for _, ch := range chs {
            if ch != nil {
                result = append(result, ch)
            }
        }
        return result
    }

Dead Ends

Common approaches that don't work:

  1. Adding a default case to the select 80% fail

    A default case will execute immediately if all channels are nil, but it doesn't solve the underlying issue of nil channels; it just avoids the block.

  2. Removing the select and using direct channel operations 95% fail

    Direct operations on nil channels will also block forever, so this doesn't help.