go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/panic-sync-negative-waitgroup-counter

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

wg.Done() called more times than wg.Add(), typically from double-decrement or Done in a loop without matching Add.

generic

中文

wg.Done() 调用次数多于 wg.Add(),通常是重复减计数或循环中 Done 未匹配 Add。

Workarounds

  1. 95% success
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
  2. 92% success
    g, ctx := errgroup.WithContext(context.Background())
    g.Go(func() error { return work(ctx) })
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Panic is thrown inside sync.WaitGroup internal state; recover in the goroutine may catch it but leaves the counter corrupted.

  2. 85% fail

    Masks the bug; wg.Wait() then blocks forever because counter never reaches zero.