go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/deadlock-waitgroup-misuse

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 100% fail

    Panic crashes the program unless recovered.

  3. 80% fail

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