go runtime_error ai_generated true

panic: 关闭已关闭的 channel

panic: close of closed channel

ID: go/close-of-closed-channel

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

版本兼容性

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

根因分析

多个代码路径对同一 channel 调用 close(ch),例如成功和错误分支中都 defer close。

English

Multiple code paths call close(ch) on the same channel, e.g. deferred close in both success and error branches.

generic

解决方案

  1. 95% 成功率
    var once sync.Once
    once.Do(func() { close(ch) })
  2. 90% 成功率
    // Only the goroutine that created ch closes it, after all producers are done via WaitGroup.

无效尝试

常见但无效的做法:

  1. 90% 失败

    len is racy and does not indicate closed state.

  2. 85% 失败

    Swallows a real logic bug; second close is still a bug.