go runtime_error ai_generated true

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

ID: go/waitgroup-reuse-before-wait

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

wg.Add is called again before a prior wg.Wait has returned, indicating the WaitGroup is being reused concurrently.

generic

中文

在上一次 wg.Wait 返回之前又调用了 wg.Add,说明 WaitGroup 被并发重用。

Workarounds

  1. 94% success
    for _, batch := range batches {
        var wg sync.WaitGroup
        for _, item := range batch {
            wg.Add(1)
            go func(i Item) { defer wg.Done(); work(i) }(item)
        }
        wg.Wait()
    }
  2. 90% success
    g := new(errgroup.Group)
    for _, item := range batch {
        g.Go(func() error { return work(item) })
    }
    g.Wait()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Sleep cannot guarantee goroutine completion and reintroduces races.

  2. 75% fail

    Reassigning wg while goroutines hold a reference to the old one causes Done to target the wrong counter.