go runtime_error ai_generated true

panic: close of closed channel

ID: go/goroutine-channel-close-multiple

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-03-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active
1.22 active

Root Cause

Calling close() on a channel that has already been closed, typically due to multiple goroutines attempting to close the same channel.

generic

中文

对已经关闭的通道再次调用close(),通常是由于多个协程试图关闭同一个通道。

Workarounds

  1. 99% success Use sync.Once to ensure close is called only once
    var closeOnce sync.Once
    closeOnce.Do(func() {
        close(ch)
    })
  2. 98% success Designate a single goroutine to close the channel
    // Only one goroutine has access to close(ch)
    ch := make(chan int)
    go func() {
        // close when done
        close(ch)
    }()

Dead Ends

Common approaches that don't work:

  1. Checking if channel is closed before closing 80% fail

    No built-in way to check if a channel is closed without risking a race condition.

  2. Using recover() to catch panic 85% fail

    Recover does not prevent the panic from occurring; it only catches it after the fact.