go runtime_error ai_generated true

panic: sync: WaitGroup 计数器为负

panic: sync: negative WaitGroup counter

ID: go/waitgroup-negative-counter

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

版本兼容性

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

根因分析

wg.Done() 被调用的次数多于 wg.Add(n)。常见于在循环中调用 Done,或某个 goroutine 退出两次。

English

wg.Done() is called more times than wg.Add(n). Common when Done is called in a loop or when a goroutine exits twice.

generic

解决方案

  1. 95% 成功率
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
  2. 93% 成功率
    g, ctx := errgroup.WithContext(ctx)
    g.Go(func() error { return work(ctx) })
    return g.Wait()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Masks the real bug; the WaitGroup may now never reach zero and Wait blocks forever.

  2. 80% 失败

    Panic in Done leaves the counter corrupted and the program in an undefined state.