go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/waitgroup-negative-counter

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success
    Ensure Add is called before starting goroutines and Done is called exactly once per goroutine.
  2. 90% success
    Use a defer statement right after Add to guarantee Done is called.

Dead Ends

Common approaches that don't work:

  1. 100% fail

    The panic will crash the program; ignoring is not possible.

  2. 80% fail

    This masks the bug and may cause Wait() to return prematurely.

  3. 70% fail

    If Add is not called, Done will still decrement and may go negative.