Golang / GoLang Concurrency Mastery Interview Questions
How does sync.WaitGroup work and what are the most common mistakes?
sync.WaitGroup is a counter-based synchronisation primitive. One goroutine calls Wait() to block until all tracked goroutines have called Done(). The counter starts at zero, increases with Add(n), and decreases with Done() (equivalent to Add(-1)).
// CORRECT usage pattern var wg sync.WaitGroup urls := []string{"http://a.com", "http://b.com", "http://c.com"} for _, url := range urls { wg.Add(1) // Add BEFORE launching â not inside the goroutine go func(u string) { defer wg.Done() // defer ensures Done fires even on panic fetchURL(u) }(url) // Pass url as argument (avoids closure trap) } wg.Wait() // blocks until counter reaches zero // MISTAKE 1: Add inside the goroutine â race with Wait // go func() { // wg.Add(1) // may execute AFTER wg.Wait() â already zero! // defer wg.Done() // }() // wg.Wait() // may return before any goroutine calls Add // MISTAKE 2: Passing WaitGroup by value // processFiles(wg) // WRONG: copies WaitGroup â broken // processFiles(&wg) // CORRECT: pass pointer // MISTAKE 3: Calling Done() more times than Add() â panic // wg.Done() // if counter is already zero, panics // PATTERN: Add all at once when count is known wg.Add(len(urls)) for _, url := range urls { go func(u string) { defer wg.Done() fetchURL(u) }(url) } wg.Wait()
More Related questions...