go runtime_error ai_generated true

panic: close of closed channel

ID: go/close-of-closed-channel

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

Two goroutines both called close(ch), or a deferred close ran twice because the function was retried. Go panics on the second close.

generic

中文

两个 goroutine 都调用了 close(ch),或函数被重试导致 defer close 执行了两次。Go 在第二次 close 时 panic。

Workarounds

  1. 97% success
    var closeOnce sync.Once
    closeOnce.Do(func() { close(ch) })
  2. 95% success
    // Only the producer closes
    func produce(ch chan<- int, n int) {
        defer close(ch)
        for i := 0; i < n; i++ { ch <- i }
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    The flag itself is racy without a mutex; two goroutines can both read false and both call close.

  2. 60% fail

    If the main goroutine is not the sole owner or the function can run concurrently, this does not guarantee single close.