go runtime_error ai_generated true

panic: WaitGroup 计数器为负

panic: sync: negative WaitGroup counter

ID: go/waitgroup-add-positive-delta

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-02-14首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.20 active — — —
1.22 active — — —

根因分析

wg.Done() 的调用次数多于 wg.Add()。通常是因为启动 goroutine 前漏了 Add、重复 defer wg.Done(),或 Done 在循环路径中执行次数超过 Add 的数量。

English

wg.Done() is called more times than wg.Add(). Usually a missing Add before launching a goroutine, a double defer wg.Done(), or Done called in a loop path that runs more than the added count.

generic

解决方案

  1. 96% 成功率
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
  2. 90% 成功率
    func launch(wg *sync.WaitGroup, f func()) {
        wg.Add(1)
        go func() { defer wg.Done(); f() }()
    }

无效尝试

常见但无效的做法:

  1. 70% 失败

    Masks the real double-Done bug and can cause Wait to hang forever if the count never reaches zero.

  2. 90% 失败

    Wait then blocks forever because the counter never decrements.