sync.Cond
sync.Cond is a condition variable: goroutines Wait until another goroutine Signals or Broadcasts. It must be used with a Locker, usually a *sync.Mutex, and a condition you check in a loop.
Detailed Explanation
A mutex protects a predicate ("the queue is not empty"). When the predicate is false, you cannot just unlock and spin. cond.Wait() unlocks, parks, and re-locks when woken. Because of spurious wakes and because another waiter may have consumed the item, you loop: for !ready { cond.Wait() }.
Signal wakes one, Broadcast wakes all. Use Signal when any one waiter can make progress (a single slot freed). Use Broadcast when the condition is global (a close, a reset). Waking with no waiters is a no-op.
You must hold the lock. Wait requires the lock held. Signal and Broadcast are typically called with the lock held so the predicate change and the wake are one critical section. The docs allow Signal without the lock; holding it is the less surprising form.
Most Go code does not need Cond. A channel already queues and wakes. WaitGroup already waits for completion. Reach for Cond when you have a shared struct, a mutex, and a predicate that is not "this channel received a value" — for example a bounded in-memory pool with several conditions (not empty and not closed).
What it costs. Cond is easy to get wrong: missing the loop, signalling the wrong cond, copying the Cond. A channel plus a mutex (or two channels) is usually clearer. Prefer Cond when you are porting a textbook monitor, and write the predicate in a comment next to the for.
Code Examples
package main
import "sync"
type queue struct {
mu sync.Mutex
cond *sync.Cond
vals []int
}
func newQueue() *queue {
q := &queue{}
q.cond = sync.NewCond(&q.mu)
return q
}
func (q *queue) Push(v int) {
q.mu.Lock()
q.vals = append(q.vals, v)
q.cond.Signal()
q.mu.Unlock()
}
func (q *queue) Pop() int {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.vals) == 0 {
q.cond.Wait()
}
v := q.vals[0]
q.vals = q.vals[1:]
return v
}
func main() {
q := newQueue()
go q.Push(1)
_ = q.Pop()
}Common Gotchas
Checking the predicate once without a loop misses a stolen wake
always `for !pred { Wait() }`.
Copying a `Cond` is forbidden after use
store `*sync.Cond`.
`Wait` without the lock held panics or corrupts the cond
`Wait` without the lock held panics or corrupts the cond
Prefer a channel if it can express the same wait
Prefer a channel if it can express the same wait