go runtime_error ai_generated true

panic: send on closed channel

ID: go/panic-send-on-closed-channel

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

A goroutine sends on a channel after another goroutine called close() on it, violating the single-closer / no-send-after-close rule.

generic

中文

某个 goroutine 在另一个 goroutine 调用 close() 之后仍向该 channel 发送数据,违反了单一关闭者/关闭后不发送的规则。

Workarounds

  1. 95% success
    done := make(chan struct{})
    go func() {
        for {
            select {
            case <-done:
                return
            case ch <- v:
            }
        }
    }()
  2. 88% success
    mu.Lock()
    if !closed {
        ch <- v
    }
    mu.Unlock()

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Recover only protects the current goroutine; other senders still panic and the channel remains closed.

  2. 90% fail

    len() is racy; the channel can be closed between the check and the send.