go
runtime_error
ai_generated
true
恐慌:向已关闭的通道发送数据
panic: send on closed channel
ID: go/goroutine-send-on-closed-channel
80%修复率
85%置信度
0证据数
2024-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
向已经关闭的通道发送数据,通常是由于多个协程发送数据时没有正确同步通道的关闭操作。
English
Sending data to a channel that has already been closed, typically due to multiple goroutines sending without proper synchronization of channel closure.
解决方案
-
95% 成功率 Use a sync.Mutex to coordinate sends and close
var mu sync.Mutex ch := make(chan int) closeCh := func() { mu.Lock() defer mu.Unlock() close(ch) } send := func(v int) { mu.Lock() defer mu.Unlock() ch <- v } -
90% 成功率 Use a select with default to avoid send on closed channel
select { case ch <- v: default: // handle failure or retry }
无效尝试
常见但无效的做法:
-
Checking channel state with a flag before sending
75% 失败
Race condition: the channel could be closed between the check and the send, leading to a panic.
-
Using recover() to catch the panic and continue
85% 失败
Recovering from a panic does not prevent data loss or corruption, and the program state may be inconsistent.