go runtime_error ai_generated true

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

ID: go/panic-sync-waitgroup-reused-before-wait

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —

Root Cause

WaitGroup.Add() is called after Wait() has started but before it returns, violating the rule that Add must not be called concurrently with Wait.

generic

中文

在 Wait() 开始但尚未返回时调用了 WaitGroup.Add(),违反了 Add 不能与 Wait 并发的规则。

Workarounds

  1. 90% success
    Ensure all Add calls happen before any Wait call. Use a single WaitGroup per logical group and don't reuse until Wait returns.
  2. 92% success
    Use errgroup.Group which manages lifecycle safely:
    g, ctx := errgroup.WithContext(ctx)
    for ... { g.Go(...) }
    return g.Wait()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Sleep does not guarantee Wait has returned; race still possible.

  2. 50% fail

    If batches overlap, the same issue can occur; requires careful lifecycle management.