go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/goroutine-waitgroup-negative-counter

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-08-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Calling Done() more times than Add(), causing WaitGroup counter to go negative.

generic

中文

调用Done()的次数超过Add(),导致WaitGroup计数器变为负数。

Workarounds

  1. 95% success 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% success Use defer wg.Done() immediately after wg.Add()
    wg.Add(1)
    go func() {
        defer wg.Done()
        // work
    }()

Dead Ends

Common approaches that don't work:

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

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

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

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