go runtime_error ai_generated true

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

ID: go/waitgroup-reused-before-wait

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.19 active
1.21 active

Root Cause

Calling wg.Add() again while a previous wg.Wait() is still in progress. The runtime detects the concurrent reuse.

generic

中文

在上一次 wg.Wait() 仍在进行时再次调用 wg.Add()。运行时会检测到这种并发复用。

Workarounds

  1. 94% success
    var wg sync.WaitGroup
    wg.Add(len(items))
    for _, it := range items { go func(i int){ defer wg.Done(); process(i) }(it) }
    wg.Wait()
  2. 88% success
    done := make(chan struct{})
    go func(){ wg.Wait(); close(done) }()
    <-done
    // safe to reuse

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Timing-dependent; under load the Wait may still be in progress.

  2. 60% fail

    Couples unrelated batches and can deadlock when one batch never completes.