go runtime_error ai_generated true

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

ID: go/panic-sync-waitgroup-is-reused-before-previous-wait-has-re

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.20 active — — —
1.23 active — — —

Root Cause

wg.Add() is called again while a previous wg.Wait() is still in progress, which is explicitly disallowed by the WaitGroup contract.

generic

中文

在上一次 wg.Wait() 尚未返回时又调用 wg.Add(),这违反了 WaitGroup 的使用约定。

Workarounds

  1. 93% success
    Create a fresh WaitGroup per batch: do not reuse the same wg across phases. var wg sync.WaitGroup once per logical group of goroutines.
  2. 90% success
    Use golang.org/x/sync/errgroup where lifecycle is bounded by Wait() returning, and never call Go() after Wait() has been invoked.

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The mutex serializes the calls but does not change the illegal reuse pattern; the panic still fires.

  2. 70% fail

    A naive channel close races with still-running goroutines and may close early, producing send-on-closed panics.