go
runtime_error
ai_generated
true
panic: sync: negative WaitGroup counter
ID: go/goroutine-negative-waitgroup-counter
80%Fix Rate
87%Confidence
0Evidence
2024-04-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Calling Done() on a WaitGroup more times than Add() was called, often due to mismatched goroutine lifecycle management.
generic中文
对WaitGroup调用Done()的次数超过Add()调用的次数,通常是由于协程生命周期管理不匹配。
Workarounds
-
98% success Ensure Add() is called exactly once per goroutine before starting it
var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { defer wg.Done() // work }() } wg.Wait() -
80% success Use atomic counter with careful increment/decrement
var counter int64 atomic.AddInt64(&counter, 1) go func() { // work atomic.AddInt64(&counter, -1) }()
Dead Ends
Common approaches that don't work:
-
Adding recover() to catch the panic
90% fail
Recover does not fix the underlying counter mismatch; it only hides the symptom.
-
Increasing Add() calls arbitrarily
85% fail
This can lead to other goroutines waiting indefinitely if Done() is not called enough times.