Go Cond: Broadcast vs Signal
In this tutorial, you'll learn about Go Cond: Broadcast vs Signal. We cover key concepts, practical examples, and best practices.
Sync.Cond usage -- Use sync.Cond for goroutines that need to wait for a condition or be notified when it changes.
The Problem
sync.Cond requires a Locker (usually Mutex). Wait() automatically unlocks the Locker and blocks. Signal wakes one waiter, Broadcast wakes all.
Wrong
var mu sync.Mutex
cond := sync.NewCond(&mu)
// Waiter:
mu.Lock()
cond.Wait() // Blocks, unlocks mu
mu.Unlock()
Output:
// Works but simple pattern
Right
type Queue struct {
items []int
cond *sync.Cond
}
func NewQueue() *Queue {
return &Queue{cond: sync.NewCond(&sync.Mutex{})}
}
func (q *Queue) Put(item int) {
q.cond.L.Lock()
defer q.cond.L.Unlock()
q.items = append(q.items, item)
q.cond.Signal() // Wake one consumer
}
func (q *Queue) Get() int {
q.cond.L.Lock()
defer q.cond.L.Unlock()
for len(q.items) == 0 {
q.cond.Wait()
}
item := q.items[0]
q.items = q.items[1:]
return item
}
Output:
// Queue with condition-based blocking
Prevention
- Cond.Wait() must be called with Locker held
- Always use for loop around Wait (spurious wakeups)
- Signal wakes one waiter (efficient)
- Broadcast wakes all waiters
- Use channel patterns instead for simple cases
Common Mistakes with sync cond
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro