go runtime_error ai_generated true

panic: sync: WaitGroup is reused before previous Wait has returned

ID: go/panic-waitgroup-misuse-add-inside-goroutine

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

wg.Add is called after wg.Wait has returned, or Add is called inside a goroutine racing with Wait.

generic

中文

在 wg.Wait 返回后又调用 wg.Add,或 Add 在 goroutine 内与 Wait 竞态调用。

Workarounds

  1. 95% success
    wg.Add(len(items))
    for _, it := range items {
        go func(x Item) { defer wg.Done(); process(x) }(it)
    }
    wg.Wait()
  2. 93% success
    g := new(errgroup.Group)
    for _, it := range items {
        it := it
        g.Go(func() error { return process(it) })
    }
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Races with Wait; Wait may observe zero counter and return early.

  2. 85% fail

    WaitGroup is not designed for reuse until Wait returns; runtime panics.