go runtime_error ai_generated true

panic: close of closed channel

ID: go/close-of-closed-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-05-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

Multiple code paths call close(ch) on the same channel, e.g. deferred close in both success and error branches.

generic

中文

多个代码路径对同一 channel 调用 close(ch),例如成功和错误分支中都 defer close。

Workarounds

  1. 95% success
    var once sync.Once
    once.Do(func() { close(ch) })
  2. 90% success
    // Only the goroutine that created ch closes it, after all producers are done via WaitGroup.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    len is racy and does not indicate closed state.

  2. 85% fail

    Swallows a real logic bug; second close is still a bug.