go
runtime_error
ai_generated
true
panic:sync:WaitGroup 计数器为负数
panic: sync: negative WaitGroup counter
ID: go/panic-sync-negative-waitgroup-counter
80%修复率
90%置信度
0证据数
2024-02-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0+ | active | — | — | — |
根因分析
wg.Done() 调用次数多于 wg.Add(),通常是重复减计数或循环中 Done 未匹配 Add。
English
wg.Done() called more times than wg.Add(), typically from double-decrement or Done in a loop without matching Add.
解决方案
-
95% 成功率
wg.Add(1) go func() { defer wg.Done() work() }() -
92% 成功率
g, ctx := errgroup.WithContext(context.Background()) g.Go(func() error { return work(ctx) }) return g.Wait()
无效尝试
常见但无效的做法:
-
80% 失败
Panic is thrown inside sync.WaitGroup internal state; recover in the goroutine may catch it but leaves the counter corrupted.
-
85% 失败
Masks the bug; wg.Wait() then blocks forever because counter never reaches zero.