🐹 Go (Golang)
Intermediate
What is sync.WaitGroup in Go?
Answer
sync.WaitGroup is used to wait for a collection of goroutines to finish. Call wg.Add(n) before launching goroutines to set the counter, wg.Done() (typically via defer wg.Done()) inside each goroutine when it completes, and wg.Wait() in the coordinating goroutine to block until the counter reaches zero. A common pattern: for _, item := range items { wg.Add(1); go func(i Item) { defer wg.Done(); process(i) }(item) }; wg.Wait(). Always call Add before launching the goroutine to avoid a race between launching and waiting.