go runtime_error ai_generated true

恐慌:同步:WaitGroup在之前的Wait返回之前被重用

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

ID: go/goroutine-waitgroup-wait-in-loop

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

版本兼容性

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

根因分析

在之前的Wait()仍在进行时对WaitGroup调用Add(),导致竞态条件。

English

Calling Add() on a WaitGroup while a previous Wait() is still in progress, causing race.

generic

解决方案

  1. 95% 成功率 Create a new WaitGroup for each batch
    for batch := 0; batch < 3; batch++ {
        var wg sync.WaitGroup
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go func() { defer wg.Done(); /* work */ }()
        }
        wg.Wait()
    }
  2. 85% 成功率 Use channels to synchronize instead of reusing WaitGroup
    ch := make(chan struct{})
    for i := 0; i < 5; i++ {
        go func() { /* work */; ch <- struct{}{} }()
    }
    for i := 0; i < 5; i++ {
        <-ch
    }

无效尝试

常见但无效的做法:

  1. Using recover() to catch panic 100% 失败

    Panic is unrecoverable in this context; program crashes.

  2. Adding more Done() calls to unblock Wait 90% 失败

    Counter imbalance causes negative counter panic.