go
runtime_error
ai_generated
true
恐慌:同步:负数WaitGroup计数器
panic: sync: negative WaitGroup counter
ID: go/goroutine-waitgroup-negative-counter
80%修复率
87%置信度
0证据数
2024-08-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
调用Done()的次数超过Add(),导致WaitGroup计数器变为负数。
English
Calling Done() more times than Add(), causing WaitGroup counter to go negative.
解决方案
-
95% 成功率 Ensure Add is called exactly once per goroutine before Done
var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() // work }() } wg.Wait() -
98% 成功率 Use defer wg.Done() immediately after wg.Add()
wg.Add(1) go func() { defer wg.Done() // work }()
无效尝试
常见但无效的做法:
-
Using recover() to catch panic and continue
90% 失败
Panic indicates misuse; recovering doesn't fix the counter imbalance.
-
Adding extra Add() calls to compensate
80% 失败
Race condition may cause unpredictable counter values; proper accounting is needed.