{
  "id": "go/waitgroup-add-inside-goroutine",
  "signature": "fatal error: all goroutines are asleep - deadlock! (WaitGroup.Wait returned before Add)",
  "signature_zh": "fatal error: 所有 goroutine 都在休眠 - 死锁！（WaitGroup.Wait 在 Add 之前返回）",
  "regex": "fatal\\ error:\\ all\\ goroutines\\ are\\ asleep\\ \\-\\ deadlock!\\ \\(WaitGroup\\.Wait\\ returned\\ before\\ Add\\)",
  "domain": "go",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "wg.Add(1) is called inside the spawned goroutine instead of before go, so wg.Wait() can observe a zero counter and return, or the program deadlocks.",
  "root_cause_type": "generic",
  "root_cause_zh": "wg.Add(1) 被放在新 goroutine 内部而不是 go 之前调用，导致 wg.Wait() 可能看到计数器为零而提前返回，或程序死锁。",
  "versions": [
    {
      "version": "1.0+",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Sleep is a race; under load the goroutine still may not have run Add before Wait.",
      "fail_rate": 0.75,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Doubling the count causes Wait to block forever or triggers a negative counter panic.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.95,
      "how": "for _, item := range items {\n    wg.Add(1)\n    go func(item Item) {\n        defer wg.Done()\n        process(item)\n    }(item)\n}\nwg.Wait()",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.93,
      "how": "g, ctx := errgroup.WithContext(context.Background())\nfor _, item := range items {\n    item := item\n    g.Go(func() error { return process(ctx, item) })\n}\nreturn g.Wait()",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.87,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-01-22",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}