go runtime_error ai_generated true

恐慌:关闭已关闭的通道

panic: close of closed channel

ID: go/close-channel-multiple-times

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

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

尝试关闭一个已经关闭的通道,通常是由于没有同步的并发关闭调用。

English

Attempting to close a channel that has already been closed, often due to concurrent close calls without synchronization.

generic

解决方案

  1. 95% 成功率
    var closeOnce sync.Once; closeOnce.Do(func() { close(ch) })
  2. 90% 成功率
    var closed bool; if !closed { close(ch); closed = true }

无效尝试

常见但无效的做法:

  1. 60% 失败

    Recover only prevents crash but doesn't fix the logic; can mask bugs.

  2. 80% 失败

    Defer executes on function exit; if close happens earlier, panic occurs.