go
runtime_error
ai_generated
true
恐慌:同步:WaitGroup计数器为负
panic: sync: negative WaitGroup counter
ID: go/goroutine-negative-waitgroup-counter
80%修复率
87%置信度
0证据数
2024-04-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
对WaitGroup调用Done()的次数超过Add()调用的次数,通常是由于协程生命周期管理不匹配。
English
Calling Done() on a WaitGroup more times than Add() was called, often due to mismatched goroutine lifecycle management.
解决方案
-
98% 成功率 Ensure Add() is called exactly once per goroutine before starting it
var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { defer wg.Done() // work }() } wg.Wait() -
80% 成功率 Use atomic counter with careful increment/decrement
var counter int64 atomic.AddInt64(&counter, 1) go func() { // work atomic.AddInt64(&counter, -1) }()
无效尝试
常见但无效的做法:
-
Adding recover() to catch the panic
90% 失败
Recover does not fix the underlying counter mismatch; it only hides the symptom.
-
Increasing Add() calls arbitrarily
85% 失败
This can lead to other goroutines waiting indefinitely if Done() is not called enough times.