go runtime_error ai_generated true

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

panic: sync: negative WaitGroup counter

ID: go/deadlock-waitgroup-misuse

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

版本兼容性

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

根因分析

调用 Done() 的次数多于 Add(),导致计数器变为负数,引发恐慌。

English

Calling Done() more times than Add() causes the counter to go negative, panicking.

generic

解决方案

  1. 95% 成功率
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        // work
    }()
    wg.Wait()
  2. 90% 成功率
    // Ensure Add is called before starting goroutines
    wg.Add(2)
    go func() { defer wg.Done(); /* work */ }()
    go func() { defer wg.Done(); /* work */ }()
    wg.Wait()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Recovery doesn't fix the logic error; program state is inconsistent.

  2. 100% 失败

    Panic crashes the program unless recovered.

  3. 80% 失败

    Doesn't prevent negative if Done is called too many times.