go runtime_error ai_generated true

panic: sync: 在之前的 Wait 返回前复用了 WaitGroup

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

ID: go/waitgroup-wait-reused

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-08-22首次发现

版本兼容性

版本状态引入弃用备注
1.20 active — — —

根因分析

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

English

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

解决方案

  1. 90% 成功率
    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% 成功率
    Ensure all goroutines have called Done before calling Add for the next round; synchronize rounds with a barrier channel.

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 80% 失败

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