go
runtime_error
ai_generated
true
恐慌:关闭已关闭的通道
panic: close of closed channel
ID: go/close-channel-twice
80%修复率
85%置信度
0证据数
2024-03-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
尝试关闭一个已经关闭的通道。
English
Attempting to close a channel that has already been closed.
解决方案
-
95% 成功率 Use sync.Once to ensure close is called only once
var closeOnce sync.Once closeOnce.Do(func() { close(ch) }) -
90% 成功率 Design with a single producer that closes the channel
Only one goroutine should close the channel; use a dedicated closer goroutine.
无效尝试
常见但无效的做法:
-
Checking if channel is closed before closing via a flag
80% 失败
Race condition: two goroutines may both see the flag as false and attempt close.
-
Using recover() to catch panic
70% 失败
recover() catches panics but closing a closed channel is a programming error; better to prevent.