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()
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
