go runtime_error ai_generated true

致命错误:所有 goroutine 都在休眠 - 死锁!(循环等待)

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

ID: go/deadlock-with-multiple-channels

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-09-01首次发现

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 90% 失败

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