sync.Cond Broadcast Wakes Every Waiter
Wake every parked goroutine at once with sync.Cond Broadcast: Signal releases a single waiter while Broadcast releases all of them.
Code
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var mu sync.Mutex
ready := sync.NewCond(&mu)
done := false
var woke atomic.Int32
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
mu.Lock()
for !done { // Wait 必须在循环里:唤醒后重查条件
ready.Wait()
}
woke.Add(1)
mu.Unlock()
fmt.Println("worker", id, "observed done")
}(id)
}
time.Sleep(50 * time.Millisecond) // 让三个等待者都先进入 Wait
mu.Lock()
done = true
ready.Broadcast() // 唤醒全部等待者;Signal 只会唤醒一个
mu.Unlock()
wg.Wait()
fmt.Println("waiters woken:", woke.Load())
}How it works
sync.Cond Broadcast Wakes Every Waiter reduces to the function main.
Iteration happens inside for id := 1; id <= 3; id++ — everything outside it runs once. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Caveats
- Self-contained — no imports beyond what the runtime already provides.
Using it
Signature: func main()
Running the file prints labeled results such as worker, waiters woken: — each operation’s effect is visible in the output.
Key statements
go func(id int) {
defer wg.Done()
mu.Lock()
for !done { // Wait 必须在循环里:唤醒后重查条件
ready.Wait()
}
woke.Add(1)
mu.Unlock()
fmt.Println("worker", id, "observed done")
}(id)
ready := sync.NewCond(&mu)
var wg sync.WaitGroup
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does sync.Cond Broadcast Wakes Every Waiter print when run?
- Run it as a complete program — the output lines carry labels such as `worker`, `waiters woken:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.