go runtime_error ai_generated true

panic: sync: 在上一次 Wait 返回前复用了 WaitGroup

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

ID: go/waitgroup-reused-before-wait

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

版本兼容性

版本状态引入弃用备注
1.19 active
1.21 active

根因分析

在上一次 wg.Wait() 仍在进行时再次调用 wg.Add()。运行时会检测到这种并发复用。

English

Calling wg.Add() again while a previous wg.Wait() is still in progress. The runtime detects the concurrent reuse.

generic

解决方案

  1. 94% 成功率
    var wg sync.WaitGroup
    wg.Add(len(items))
    for _, it := range items { go func(i int){ defer wg.Done(); process(i) }(it) }
    wg.Wait()
  2. 88% 成功率
    done := make(chan struct{})
    go func(){ wg.Wait(); close(done) }()
    <-done
    // safe to reuse

无效尝试

常见但无效的做法:

  1. 85% 失败

    Timing-dependent; under load the Wait may still be in progress.

  2. 60% 失败

    Couples unrelated batches and can deadlock when one batch never completes.