sync.Cond by example — wait, signal, and broadcast

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// condition variable with its mutex
c := sync.NewCond(&sync.Mutex{})
var ready int

// spawn 10 goroutines; each waits a random time, marks ready (under the lock)
for i := 0; i < 10; i++ {
go func(i int) {
time.Sleep(time.Duration(rand.Int63n(5)) * time.Second)

c.L.Lock()
ready++
c.L.Unlock()

log.Printf("athlete #%d is ready\n", i)
// wake everyone waiting on the condition
// Signal would work too — only main is waiting
c.Broadcast()
}(i)
}

// wait until all 10 are ready
c.L.Lock()
for ready != 10 {
c.Wait()
log.Println("starter woke once")
}
c.L.Unlock()

log.Println("all athletes ready. On your marks, 3, 2, 1, ...")

Typical log lines:

1
2
3
4
2021/08/09 21:26:04 athlete #0 is ready
2021/08/09 21:26:04 starter woke once
...
2021/08/09 21:26:13 all athletes ready. On your marks, 3, 2, 1, ...

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
2
3
4
5
6
7
8
9
10
11
func (c *Cond) Wait() {
c.checker.check()
// enqueue this goroutine on the notify list
t := runtime_notifyListAdd(&c.notify)
// release the lock so other goroutines can make progress
c.L.Unlock()
// park until notified
runtime_notifyListWait(&c.notify, t)
// re-acquire the lock before returning
c.L.Lock()
}

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
2
3
4
5
6
//  c.L.Lock()
// for !condition() {
// c.Wait()
// }
// ... make use of condition ...
// c.L.Unlock()

Channels can approximate the same idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// unbuffered
ch := make(chan int)
for i := 0; i < 10; i++ {
go func(i int) {
ch <- 1 // i is ready
}(i)
}

for i := 0; i < 10; i++ {
<-ch
}
println("all is ready!")


// buffered
ch := make(chan int, 10)
for i := 0; i < 10; i++ {
go func(i int) {
ch <- i
}(i)
}

for len(ch) != 10 {
time.Sleep(time.Millisecond)
}
println("all is ready!")

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