~/Go sync.Cond Explained for Concurrent Goroutines

Jul 11, 2022


A Go sync.Cond allows goroutines to wait for or signal the occurrence of an event. It is built on top of a Locker, typically a Mutex.

Basic usage:

Common pattern for usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Example using sync.Cond
var mu sync.Mutex
cond := sync.NewCond(&mu)
ready := false

go func() {
    mu.Lock()
    for !ready {
        cond.Wait()
    }
    mu.Unlock()
}()

mu.Lock()
ready = true
cond.Signal() // or cond.Broadcast()
mu.Unlock()

Always check conditions in a loop. The condition may not be true when unblocked. Learn why.

Alternatives: For simple cases, channels are easier. Signal mirrors sending on a channel, and Broadcast mirrors closing.

Notes:

Further reading

Use sync.Cond for advanced coordination, mostly when channels do not fit the need.

Tags: [go] [concurrency] [synchronization]