go runtime_error ai_generated true

恐慌:同步:负数WaitGroup计数器

panic: sync: negative WaitGroup counter

ID: go/goroutine-waitgroup-negative-counter

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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()
  2. 98% 成功率 Use defer wg.Done() immediately after wg.Add()
    wg.Add(1)
    go func() {
        defer wg.Done()
        // work
    }()

无效尝试

常见但无效的做法:

  1. Using recover() to catch panic and continue 90% 失败

    Panic indicates misuse; recovering doesn't fix the counter imbalance.

  2. Adding extra Add() calls to compensate 80% 失败

    Race condition may cause unpredictable counter values; proper accounting is needed.