go runtime_error ai_generated true

panic: close of closed channel

ID: go/close-channel-twice

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Attempting to close a channel that has already been closed.

generic

中文

尝试关闭一个已经关闭的通道。

Workarounds

  1. 95% success Use sync.Once to ensure close is called only once
    var closeOnce sync.Once
    closeOnce.Do(func() { close(ch) })
  2. 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:

  1. 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.

  2. Using recover() to catch panic 70% fail

    recover() catches panics but closing a closed channel is a programming error; better to prevent.