go
runtime_error
ai_generated
true
panic: runtime error: send on closed channel (context cancellation)
ID: go/context-cancellation-ignore
80%Fix Rate
87%Confidence
0Evidence
2024-09-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.7 | active | — | — | — |
| 1.23 | active | — | — | — |
Root Cause
When a context is cancelled, its channel is closed; sending on it causes a panic.
generic中文
当上下文被取消时,其通道被关闭;向其发送数据会导致恐慌。
Workarounds
-
95% success Use select with context.Done() to avoid sending on closed channel
select { case ch <- data: case <-ctx.Done(): return ctx.Err() } -
90% success 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() }
Dead Ends
Common approaches that don't work:
-
Checking context.Err() before send but not handling race condition
70% fail
Context can be cancelled between check and send.
-
Using a separate channel that is not closed on cancellation
60% fail
Ignores the cancellation signal, leading to resource leaks.