go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/negative-waitgroup-counter

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Calling Done() more times than Add() was called, decrementing counter below zero.

generic

中文

调用 Done() 的次数多于 Add() 的次数,导致计数器减到负数。

Workarounds

  1. 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()
  2. 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:

  1. Increasing Add() count arbitrarily 85% fail

    If Done() is called extra times, the counter still goes negative.

  2. Ignoring the panic and continuing 100% fail

    Panic stops execution; ignoring it is not possible.