a common mistake when using Sync Mutex Basics
Fast recall
Quick revision
Core answer
Practical understanding of Sync Mutex Basics.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
The WaitGroup is the join primitive:
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done() // fires when this goroutine returns
work(n)
}(i)
}
wg.Wait() // blocks until counter = 0
fmt.Println("all done")Executed: workers 1, 2, 3 finished in order (simulated with delays), then 'all done'.
The three methods:
- Add(n): increments. BEFORE the spawn (Add after go is a race).
- Done(): decrements by 1. defer wg.Done() — runs on every exit path.
- Wait(): blocks until 0. Multiple goroutines can Wait on the same group.
The reuse rule: after Wait returns, the WaitGroup is reusable (counter is 0). Add while Wait is active is the classic deadlock.
The standard use is fan-out/fan-in: spawn N with Add(1), collect via channel or shared slice under mutex, Wait, then use the results.
a common mistake when using Sync Mutex Basics
Direct Answer
wg.Add(1) before spawning, defer wg.Done() inside, wg.Wait() to block until all Done calls have fired. Counter-based: Add increments, Done decrements, Wait blocks at zero.
Deep Dive & Architecture
The counter mechanics: WaitGroup is a single integer plus a semaphore. Add atomically increments; Done decrements and signals at zero; Wait parks on the semaphore until signaled. No goroutine-identity tracking — 'N completions,' anonymous and composable.
The ordering bug interviewers probe — Add inside the spawned goroutine:
for i := 0; i < N; i++ {
go func() { wg.Add(1); defer wg.Done(); work() }() // BUG
}
wg.Wait()
Main might reach Wait before ANY spawned goroutine reaches Add — counter was 0 when Wait checked, Wait returns immediately, results aren't ready. The fix: Add before go — the happens-before chain: Add → spawn → work → Done → 0 → Wait wakes.
The nested pattern: one WaitGroup per 'barrier' — a set of work that must complete before the next phase — with channels carrying the results. WaitGroups compose via counting, not nesting.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Sync Mutex Basics, and when would you use it?
- When would you use Sync Mutex Basics in a real project?
- How would you compare Sync Mutex Basics with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.