# WaitGroup Misuse - ID: go-waitgroup-misuse - Severity: HIGH - CWE: Race Condition (CWE-362) - Languages: Go ## Description Improper use of sync.WaitGroup can cause race conditions, panics, or deadlocks. Common issues include calling Add() inside goroutines and Done() count mismatches. ## Detection Message Improper WaitGroup usage can cause: - Race conditions (Add inside goroutine) - Panics (negative counter from Done miscount) - Deadlocks (Wait before Add completes) ## Remediation 1. Always Add() BEFORE starting goroutine: ```go wg.Add(1) go func() { defer wg.Done() // work }() ``` 2. Always use defer wg.Done() to ensure it runs: ```go go func() { defer wg.Done() // Runs even if panic occurs work() }() ``` 3. Consider using errgroup for better error handling: ```go g, ctx := errgroup.WithContext(ctx) g.Go(func() error { return work() }) err := g.Wait() ``` ## Documentation [object Object] ## Related Rules - **Concurrent Slice Access** [HIGH]: - **Direct Map Access on Thread-Safe Struct** [HIGH]: - **Potential Race Condition** [MEDIUM]: - **Race Condition in Concurrent Operations** [HIGH]: - **Potential Race Condition** [MEDIUM]: