go runtime_error ai_generated true

panic: close of closed channel

ID: go/channel-close-twice

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Attempting to close a channel that has already been closed, usually due to multiple goroutines closing without coordination.

generic

中文

尝试关闭已经关闭的通道,通常由于多个goroutine没有协调就关闭通道。

Workarounds

  1. 95% success
    Use sync.Once to ensure the channel is closed only once.
  2. 90% success
    Have a single owner goroutine that is responsible for closing the channel.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The panic is fatal and cannot be recovered; it will crash the program.

  2. 85% fail

    Checking a flag is racy; the channel may be closed between the check and the close call.

  3. 60% fail

    The mutex ensures only one goroutine closes, but it does not prevent closing an already closed channel if the logic is wrong.