go
runtime_error
ai_generated
true
panic: sync: WaitGroup 计数器为负
panic: sync: negative WaitGroup counter
ID: go/waitgroup-negative-counter
80%修复率
90%置信度
0证据数
2024-04-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
wg.Done() 被调用的次数多于 wg.Add(n)。常见于在循环中调用 Done,或某个 goroutine 退出两次。
English
wg.Done() is called more times than wg.Add(n). Common when Done is called in a loop or when a goroutine exits twice.
解决方案
-
95% 成功率
wg.Add(1) go func() { defer wg.Done() work() }() -
93% 成功率
g, ctx := errgroup.WithContext(ctx) g.Go(func() error { return work(ctx) }) return g.Wait()
无效尝试
常见但无效的做法:
-
70% 失败
Masks the real bug; the WaitGroup may now never reach zero and Wait blocks forever.
-
80% 失败
Panic in Done leaves the counter corrupted and the program in an undefined state.