go
runtime_error
ai_generated
true
panic: close of closed channel
ID: go/close-channel-twice
80%Fix Rate
85%Confidence
0Evidence
2024-03-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Attempting to close a channel that has already been closed.
generic中文
尝试关闭一个已经关闭的通道。
Workarounds
-
95% success Use sync.Once to ensure close is called only once
var closeOnce sync.Once closeOnce.Do(func() { close(ch) }) -
90% success Design with a single producer that closes the channel
Only one goroutine should close the channel; use a dedicated closer goroutine.
Dead Ends
Common approaches that don't work:
-
Checking if channel is closed before closing via a flag
80% fail
Race condition: two goroutines may both see the flag as false and attempt close.
-
Using recover() to catch panic
70% fail
recover() catches panics but closing a closed channel is a programming error; better to prevent.