go runtime_error ai_generated true

panic: sync: negative WaitGroup counter

ID: go/waitgroup-negative-counter

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.21 active

Root Cause

wg.Done() is called more times than wg.Add(n). Common when Done is called in a loop or when a goroutine exits twice.

generic

中文

wg.Done() 被调用的次数多于 wg.Add(n)。常见于在循环中调用 Done,或某个 goroutine 退出两次。

Workarounds

  1. 95% success
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
  2. 93% success
    g, ctx := errgroup.WithContext(ctx)
    g.Go(func() error { return work(ctx) })
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Masks the real bug; the WaitGroup may now never reach zero and Wait blocks forever.

  2. 80% fail

    Panic in Done leaves the counter corrupted and the program in an undefined state.