Use sync.Cond to block goroutines until a specific condition is met by wrapping a sync.Mutex and signaling with Signal or Broadcast.
import "sync"
var (
mu sync.Mutex
cond = sync.NewCond(&mu)
ready = false
)
// Waiter blocks until ready is true
func wait() {
mu.Lock()
for !ready {
cond.Wait()
}
// Critical section
mu.Unlock()
}
// Signaler sets ready and wakes one waiter
func signal() {
mu.Lock()
ready = true
cond.Signal()
mu.Unlock()
}
The Wait() method atomically unlocks the mutex and blocks until Signal() or Broadcast() is called. Always check the condition in a loop because spurious wakeups can occur.