go runtime_error ai_generated true

panic:sync:WaitGroup 在上一次 Wait 返回前被重用

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

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 92% 成功率
    wg.Add(n)
    for i := 0; i < n; i++ {
        go worker(&wg)
    }
    wg.Wait()
  2. 90% 成功率
    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()
    }

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 80% 失败

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