Wait on conditions with Cond
Wait on conditions with Cond
A condition variable coordinates waiting for shared state. Create sync.NewCond with a locker, check the predicate while holding that locker, and call Wait in a loop. Wait atomically unlocks the locker and suspends the caller, then reacquires it before returning. The predicate, not the notification, decides whether work can proceed.
package main
import ( "fmt" "sync")
func main() { var mu sync.Mutex c := sync.NewCond(&mu) ready := false done := make(chan struct{}) go func() { mu.Lock() for !ready { c.Wait() } mu.Unlock() close(done) }() mu.Lock() ready = true c.Broadcast() mu.Unlock() <-done fmt.Println("ready")}Even if the producer sets ready before the waiter starts, the waiter sees the predicate and skips Wait. Signal wakes one waiting goroutine; Broadcast wakes all current waiters. Notifications are not stored for future waiters. Go Wait cannot return without Signal or Broadcast, but another worker may change the predicate before a woken worker reacquires the lock. Hence use for, not if.
Expected output:
readyWait for an available item
package main
import ( "fmt" "sync")
func main() { var mu sync.Mutex c := sync.NewCond(&mu) queue := []int{} out := make(chan int, 1) go func() { mu.Lock() for len(queue) == 0 { c.Wait() } v := queue[0] queue = queue[1:] mu.Unlock() out <- v }() mu.Lock() queue = append(queue, 7) c.Signal() mu.Unlock() fmt.Println(<-out)}Both reading and changing queue are protected by mu. Signal is sufficient here because exactly one worker consumes one item. For simple one-time events, closing a channel is often simpler; Cond is useful for reusable predicates under a lock. A context is not automatically observed by Wait; cancellation needs an explicit design.
Expected output:
7Try it locally
Start two waiters that wait until count reaches 2. Set count under the mutex and Broadcast. Join both with WaitGroup, then print "both ready".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 05: Wait on conditions with Cond
Check the lesson objective before moving on.
What does Wait do with its locker?
Why check the predicate in a loop?