go runtime_error ai_generated true

panic: send on closed channel

ID: go/send-on-closed-channel

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Sending data to a channel that has been closed.

generic

中文

向已经关闭的通道发送数据。

Workarounds

  1. 95% success Ensure no sends after close by using a done channel pattern
    done := make(chan struct{})
    // producer loop
    select {
    case <-done:
        return
    case ch <- data:
    }
    // closer
    close(ch); close(done)
  2. 90% success Use a mutex to synchronize close and sends
    var mu sync.Mutex
    var closed bool
    mu.Lock()
    if closed { mu.Unlock(); return }
    ch <- data
    mu.Unlock()

Dead Ends

Common approaches that don't work:

  1. Checking if channel is closed before sending via a flag 85% fail

    Race condition: the channel may be closed between the check and the send.

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

    Recovering from panic is possible but indicates design flaw; data may be lost.