go
runtime_error
ai_generated
true
恐慌:运行时错误:向已关闭的通道发送数据(上下文取消)
panic: runtime error: send on closed channel (context cancellation)
ID: go/context-cancellation-ignore
80%修复率
87%置信度
0证据数
2024-09-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.7 | active | — | — | — |
| 1.23 | active | — | — | — |
根因分析
当上下文被取消时,其通道被关闭;向其发送数据会导致恐慌。
English
When a context is cancelled, its channel is closed; sending on it causes a panic.
解决方案
-
95% 成功率 Use select with context.Done() to avoid sending on closed channel
select { case ch <- data: case <-ctx.Done(): return ctx.Err() } -
90% 成功率 Create a new channel for each operation and close it safely
ch := make(chan int, 1) select { case ch <- data: case <-ctx.Done(): close(ch) return ctx.Err() }
无效尝试
常见但无效的做法:
-
Checking context.Err() before send but not handling race condition
70% 失败
Context can be cancelled between check and send.
-
Using a separate channel that is not closed on cancellation
60% 失败
Ignores the cancellation signal, leading to resource leaks.