go
runtime_error
ai_generated
true
恐慌:向已关闭的通道发送数据
panic: send on closed channel
ID: go/panic-runtime-error-send-on-closed-channel
85%修复率
85%置信度
1证据数
2023-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
| go1.23 | active | — | — | — |
根因分析
尝试向已关闭的通道发送值,违反了通道的使用约定。
English
Attempting to send a value on a channel that has already been closed, which violates the channel contract.
官方文档
https://go.dev/ref/spec#Close解决方案
-
Ensure the channel is closed only by the sender after all sends are complete. Use a sync.WaitGroup to coordinate goroutines, and close the channel in a dedicated goroutine after Wait.
-
Use a select statement with a default case to check if the channel is closed before sending, or use a separate closed channel for signaling.
无效尝试
常见但无效的做法:
-
Adding a time.Sleep before closing the channel to avoid race conditions.
85% 失败
Race conditions are timing-dependent; adding sleep does not guarantee ordering and may hide the bug rather than fix it.
-
Using recover() in a deferred function to catch the panic.
70% 失败
Recovering from a panic does not fix the root cause; the channel was already misused and data may be lost.
-
Closing the channel after all sends are done by adding a sync.WaitGroup but not calling WaitGroup.Wait() correctly.
60% 失败
Incorrect WaitGroup usage leads to same race: close happens before all sends complete.