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
90%Confidence
0Evidence
2024-05-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.13 active
1.21 active

Root Cause

A producer goroutine sends to a channel that has already been closed by another goroutine (or by itself). Classic with fan-in patterns where a coordinator closes the channel too early.

generic

中文

生产者 goroutine 向已被其他 goroutine(或自身)关闭的通道发送数据。常见于协调者过早关闭通道的扇入模式。

Workarounds

  1. 93% success
    select {
    case ch <- v:
    case <-ctx.Done():
        return
    }
  2. 90% success
    done := make(chan struct{})
    go func() {
        defer close(ch)
        for {
            select {
            case <-done: return
            case ch <- next(): 
            }
        }
    }()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    A closed channel is always ready to receive; select will still pick the closed case and send panics.

  2. 55% fail

    Correct but often forgotten on one path; still panics if any send path bypasses the mutex, and adds contention.