go runtime_error ai_generated true

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

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

wg.Add() was called concurrently with wg.Wait(), or the WaitGroup was reused before all Wait calls returned. This is a race between Add and Wait.

generic

中文

wg.Add() 与 wg.Wait() 并发执行,或在所有 Wait 返回前重用了 WaitGroup。这是 Add 与 Wait 之间的竞态。

Workarounds

  1. 92% success
    wg.Add(n)
    for i := 0; i < n; i++ {
        go worker(&wg)
    }
    wg.Wait()
  2. 90% success
    for _, batch := range batches {
        var wg sync.WaitGroup
        wg.Add(len(batch))
        for _, item := range batch {
            go func(it Item) { defer wg.Done(); process(it) }(item)
        }
        wg.Wait()
    }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Sleep doesn't establish happens-before ordering; the race can still occur and only masks the bug intermittently.

  2. 80% fail

    Sharing one WaitGroup across independent operations increases the chance of Add/Wait overlap, worsening the race.