go runtime_error ai_generated true

错误:通道已关闭但读取无限返回零值

error: channel closed but reads return zero values indefinitely

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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