~/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:
- Create a Cond with
NewCond(Locker)
. - Use
Wait
to block until a signal. - Use
Signal
to wake one waiter. - Use
Broadcast
to wake all waiters.
Common pattern for usage:
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:
- Do not copy a Cond once used.
Wait
releases the lock and suspends your goroutine until another goroutine callsSignal
orBroadcast
.- Locker must be held when observing or changing the condition.
Further reading
Use sync.Cond for advanced coordination, mostly when channels do not fit the need.