go runtime_error ai_generated true

panic: sync: WaitGroup 误用: Add 与 Wait 并发调用

panic: sync: WaitGroup misuse: Add called concurrently with Wait

ID: go/context-cancellation-race

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

版本兼容性

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

根因分析

在 Wait() 并发调用 Add(),通常是因为取消 context 导致在等待时启动了新的 goroutine。

English

Calling Add() on a WaitGroup concurrently with Wait(), often due to canceling context that triggers new goroutines while waiting.

generic

解决方案

  1. 95% 成功率
    Ensure all Add calls happen before Wait by using a separate goroutine to start workers: 
    
    var wg sync.WaitGroup
    for i := 0; i < n; i++ {
        wg.Add(1)
        go func() { defer wg.Done(); /* work */ }()
    }
    wg.Wait()
  2. 90% 成功率
    Use a channel to signal completion instead of WaitGroup when dynamic goroutine creation is needed.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Doesn't prevent Add from being called after Wait has started.

  2. 60% 失败

    If goroutines are started from a context cancellation callback, it may be too late.