go
runtime_error
ai_generated
true
恐慌:向已关闭的通道发送数据
panic: send on closed channel
ID: go/send-on-closed-channel
80%修复率
85%置信度
0证据数
2024-04-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
向已经关闭的通道发送数据。
English
Sending data to a channel that has been closed.
解决方案
-
95% 成功率 Ensure no sends after close by using a done channel pattern
done := make(chan struct{}) // producer loop select { case <-done: return case ch <- data: } // closer close(ch); close(done) -
90% 成功率 Use a mutex to synchronize close and sends
var mu sync.Mutex var closed bool mu.Lock() if closed { mu.Unlock(); return } ch <- data mu.Unlock()
无效尝试
常见但无效的做法:
-
Checking if channel is closed before sending via a flag
85% 失败
Race condition: the channel may be closed between the check and the send.
-
Using recover() to catch panic and continue
70% 失败
Recovering from panic is possible but indicates design flaw; data may be lost.