sync.Cond
Use `sync.Cond` when goroutines wait on state transitions protected by a mutex, especially when channels fit poorly.
Canonical guidance
- use
sync.Condfor condition waiting on shared state - always wait in a loop
- hold the mutex while checking and updating the condition
Use when
- one state change wakes many waiters
- polling would be wasteful
- channels would create awkward ownership or fan-out
Avoid
- calling
Waitwithout a loop - using
sync.Condwhen a simple channel close would do - guarding the condition with different locks
Preferred pattern
mu := sync.Mutex{}
cond := sync.NewCond(&mu)
ready := false
mu.Lock()
for !ready {
cond.Wait()
}
mu.Unlock()
Anti-pattern
- treating
Signalas if it permanently makes the condition true
Explanation: This anti-pattern is tempting because wake-ups feel definitive, but the real contract is the shared condition, not the wake-up event itself.
Why
sync.Condis low-level but sometimes the cleanest fit for shared-state coordination
Related pages
Sources
- sync package - Go Team
- Forgetting about sync.Cond (#72) - Teiva Harsanyi