I recently read Ma Que’s Go Concurrency in Practice course and plan to revisit the concurrency primitives with small examples. Today: sync.Cond.
Cond is for wait/notify patterns: goroutines block in Wait while a condition is false; when it becomes true, Signal wakes one waiter or Broadcast wakes all of them.
Picture ten athletes on the track — the starter fires the gun only after everyone is ready:
1 | // condition variable with its mutex |
Typical log lines:
1 | 2021/08/09 21:26:04 athlete #0 is ready |
Any goroutine that updates or checks the condition needs the mutex so reads and writes stay consistent.
Wait is special: lock, then loop. Why? From the runtime:
1 | func (c *Cond) Wait() { |
Before parking, Wait unlocks so other goroutines are not deadlocked. After wake-up it holds the lock again — but other goroutines may have run and changed the condition between Signal/Broadcast and your return, so you must re-check in a loop:
1 | // c.L.Lock() |
Channels can approximate the same idea:
1 | // unbuffered |
Cond gives you both Signal and Broadcast. A channel is usually one style or the other (close is like broadcast, but only once).
WaitGroup waits for a fixed count of goroutines. Cond cares about a boolean condition and does not require knowing how many waiters exist.
For a livelock hallway demo built with Cond, see fig-livelock-hallway from Concurrency in Go.
More Dig101 posts: /categories/go/.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
