go
runtime_error
ai_generated
true
panic: sync: negative WaitGroup counter
ID: go/negative-waitgroup-counter
80%Fix Rate
85%Confidence
0Evidence
2024-02-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Calling Done() more times than Add() was called, decrementing counter below zero.
generic中文
调用 Done() 的次数多于 Add() 的次数,导致计数器减到负数。
Workarounds
-
95% success Ensure Add() is called exactly once per goroutine that will call Done()
var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { defer wg.Done(); work() }() } wg.Wait() -
90% success Use defer wg.Done() immediately after wg.Add() in the goroutine
go func() { defer wg.Done(); ... }()
Dead Ends
Common approaches that don't work:
-
Increasing Add() count arbitrarily
85% fail
If Done() is called extra times, the counter still goes negative.
-
Ignoring the panic and continuing
100% fail
Panic stops execution; ignoring it is not possible.