go runtime_error ai_generated true

panic: send on closed channel

ID: go/channel-send-on-closed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Sending data to a channel that has been closed by another goroutine without proper synchronization.

generic

中文

在另一个goroutine关闭通道后,没有正确同步就向该通道发送数据。

Workarounds

  1. 85% success
    Ensure the sender knows when to stop. Use a done channel to signal closure, and only close the channel from the sender side.
  2. 90% success
    Use sync.Once to close the channel only once, ensuring no other sender attempts to send after close.

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. 95% fail

    len() does not indicate whether a channel is closed, only the number of buffered elements.

  3. 70% fail

    The close operation may still race with the send; mutex does not prevent closing while sending.