go
runtime_error
ai_generated
true
panic: WaitGroup 计数器为负
panic: sync: negative WaitGroup counter
ID: go/waitgroup-add-positive-delta
80%修复率
88%置信度
0证据数
2024-02-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
wg.Done() 的调用次数多于 wg.Add()。通常是因为启动 goroutine 前漏了 Add、重复 defer wg.Done(),或 Done 在循环路径中执行次数超过 Add 的数量。
English
wg.Done() is called more times than wg.Add(). Usually a missing Add before launching a goroutine, a double defer wg.Done(), or Done called in a loop path that runs more than the added count.
解决方案
-
96% 成功率
wg.Add(1) go func() { defer wg.Done() work() }() -
90% 成功率
func launch(wg *sync.WaitGroup, f func()) { wg.Add(1) go func() { defer wg.Done(); f() }() }
无效尝试
常见但无效的做法:
-
70% 失败
Masks the real double-Done bug and can cause Wait to hang forever if the count never reaches zero.
-
90% 失败
Wait then blocks forever because the counter never decrements.