go
runtime_error
ai_generated
true
panic: send on closed channel
ID: go/goroutine-send-on-closed-channel
80%Fix Rate
85%Confidence
0Evidence
2024-01-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Sending data to a channel that has already been closed, typically due to multiple goroutines sending without proper synchronization of channel closure.
generic中文
向已经关闭的通道发送数据,通常是由于多个协程发送数据时没有正确同步通道的关闭操作。
Workarounds
-
95% success 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% success Use a select with default to avoid send on closed channel
select { case ch <- v: default: // handle failure or retry }
Dead Ends
Common approaches that don't work:
-
Checking channel state with a flag before sending
75% fail
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% fail
Recovering from a panic does not prevent data loss or corruption, and the program state may be inconsistent.