go
runtime_error
ai_generated
true
panic: sync: negative WaitGroup counter
ID: go/goroutine-waitgroup-negative-counter
80%Fix Rate
87%Confidence
0Evidence
2024-08-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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() -
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:
-
Using recover() to catch panic and continue
90% fail
Panic indicates misuse; recovering doesn't fix the counter imbalance.
-
Adding extra Add() calls to compensate
80% fail
Race condition may cause unpredictable counter values; proper accounting is needed.