go runtime_error ai_generated true

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

ID: go/waitgroup-wait-reused

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active — — —

Root Cause

wg.Add() is called to reuse a WaitGroup while a prior wg.Wait() has not yet returned. The runtime detects the counter being reused and panics to prevent silent miscounting.

generic

中文

在之前的 wg.Wait() 尚未返回时调用 wg.Add() 复用 WaitGroup。运行时检测到计数器被复用并 panic,以防静默计数错误。

Workarounds

  1. 90% success
    Use a fresh WaitGroup per batch instead of reusing:
    var wg sync.WaitGroup
    for _, batch := range batches {
        wg = sync.WaitGroup{}
        // Add/Go/Wait for this batch
    }
  2. 85% success
    Ensure all goroutines have called Done before calling Add for the next round; synchronize rounds with a barrier channel.

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The reuse still happens concurrently; the panic is about ordering, not the calling goroutine.

  2. 80% fail

    Copying a WaitGroup that has been used is unsafe and may race with the in-flight Wait.