go runtime_error ai_generated true

error: WaitGroup 误用: Add 与 Wait 并发调用

error: WaitGroup misuse: Add called concurrently with Wait

ID: go/waitgroup-add-after-wait

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

版本兼容性

版本状态引入弃用备注
1.x active — — —

根因分析

一个 goroutine 在调用 wg.Add 时,另一个 goroutine 正在 wg.Wait 中,这是 sync 包明确禁止的,会导致竞态或 panic。

English

wg.Add is invoked from a goroutine while another goroutine is inside wg.Wait, which the sync package explicitly forbids and can race or panic.

generic

解决方案

  1. 95% 成功率
    wg.Add(len(tasks))
    for _, t := range tasks {
        go func(t Task) { defer wg.Done(); run(t) }(t)
    }
    wg.Wait()
  2. 92% 成功率
    jobs := make(chan Job)
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() { defer wg.Done(); for j := range jobs { run(j) } }()
    }
    for _, j := range all { jobs <- j }
    close(jobs)
    wg.Wait()

无效尝试

常见但无效的做法:

  1. 80% 失败

    Deadlocks: Wait holds the lock while waiting for Done, but Done is inside the locked section.

  2. 60% 失败

    Over-counting causes Done panics; under-counting returns early.