go runtime_error ai_generated true

error: channel closed but reads return zero values indefinitely

ID: go/receive-on-closed-channel-loop

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-07-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

Reading from a closed channel never blocks; it returns the zero value and ok=false immediately. A for-range loop only exits when the channel is closed, but a manual <-ch in a loop spins forever.

generic

中文

从已关闭的通道读取不会阻塞,会立即返回零值和 ok=false。for-range 循环仅在通道关闭时退出,但手动在循环里使用 <-ch 会无限自旋。

Workarounds

  1. 95% success
    for {
        v, ok := <-ch
        if !ok { break }
        process(v)
    }
  2. 98% success
    for v := range ch {
        process(v)
    }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Reduces CPU burn but the loop still never terminates; the program hangs and leaks goroutines.

  2. 85% fail

    len returns buffered items, not closure state. A closed empty channel has len 0, same as an open empty one.