go runtime_error ai_generated true

panic: close of closed channel

ID: go/close-channel-multiple-times

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to close a channel that has already been closed, often due to concurrent close calls without synchronization.

generic

中文

尝试关闭一个已经关闭的通道,通常是由于没有同步的并发关闭调用。

Workarounds

  1. 95% success
    var closeOnce sync.Once; closeOnce.Do(func() { close(ch) })
  2. 90% success
    var closed bool; if !closed { close(ch); closed = true }

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Recover only prevents crash but doesn't fix the logic; can mask bugs.

  2. 80% fail

    Defer executes on function exit; if close happens earlier, panic occurs.