go
runtime_error
ai_generated
true
恐慌:sync:负的 WaitGroup 计数器
panic: sync: negative WaitGroup counter
ID: go/negative-waitgroup-counter
80%修复率
85%置信度
0证据数
2024-02-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
调用 Done() 的次数多于 Add() 的次数,导致计数器减到负数。
English
Calling Done() more times than Add() was called, decrementing counter below zero.
解决方案
-
95% 成功率 Ensure Add() is called exactly once per goroutine that will call Done()
var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { defer wg.Done(); work() }() } wg.Wait() -
90% 成功率 Use defer wg.Done() immediately after wg.Add() in the goroutine
go func() { defer wg.Done(); ... }()
无效尝试
常见但无效的做法:
-
Increasing Add() count arbitrarily
85% 失败
If Done() is called extra times, the counter still goes negative.
-
Ignoring the panic and continuing
100% 失败
Panic stops execution; ignoring it is not possible.