go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (circular wait)

ID: go/deadlock-with-multiple-channels

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Multiple goroutines are waiting on each other's channels, forming a circular dependency that cannot be resolved.

generic

中文

多个 goroutine 在相互等待对方的通道,形成无法解决的循环依赖。

Workarounds

  1. 85% success
    select {
    case v := <-ch1:
        fmt.Println(v)
    case <-time.After(time.Second):
        fmt.Println("timeout")
    }
  2. 90% success
    type Coordinator struct {
        ch chan int
    }
    
    func (c *Coordinator) Run() {
        for v := range c.ch {
            go func(v int) {
                // process
            }(v)
        }
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Buffering only delays the deadlock; it doesn't break the circular wait.

  2. 90% fail

    Sleeping doesn't guarantee the order; the race condition remains.