go runtime_error ai_generated true

fatal error: 所有 goroutine 都处于休眠状态 - 死锁!(wg.Wait 在 goroutine 启动前返回)

fatal error: all goroutines are asleep - deadlock! (wg.Wait returns before goroutines start)

ID: go/waitgroup-add-inside-goroutine-race

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

版本兼容性

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

根因分析

wg.Add(1) 在 goroutine 内部调用而不是之前,导致 Wait() 可能提前返回或永久阻塞,取决于时序。

English

wg.Add(1) is called inside the goroutine rather than before it, so Wait() can return early or block forever depending on timing.

generic

解决方案

  1. 98% 成功率
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
    wg.Wait()
  2. 90% 成功率
    done := make(chan struct{}, n)
    for i := 0; i < n; i++ {
        go func() { work(); done <- struct{}{} }()
    }
    for i := 0; i < n; i++ { <-done }

无效尝试

常见但无效的做法:

  1. 80% 失败

    Sleeping only hides the race; under load the goroutine may still not have run Add in time.

  2. 75% 失败

    Serialization does not guarantee the goroutine has executed Add before Wait checks the counter.