Sync Cond Wait And Signal
Coordinate goroutines with sync.Cond: waiters park in a loop until a producer changes the guarded condition and calls Signal.
Code
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mu sync.Mutex
dataReady := sync.NewCond(&mu)
data := 0
hasData := false
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
mu.Lock()
// Wait 必须放在循环里:被唤醒后重新检查条件
for !hasData {
dataReady.Wait()
}
fmt.Println("consumer got:", data)
mu.Unlock()
}()
go func() {
defer wg.Done()
time.Sleep(20 * time.Millisecond) // 让消费者先进入 Wait
mu.Lock()
data = 42
hasData = true
dataReady.Signal() // 唤醒一个等待者
mu.Unlock()
}()
wg.Wait()
fmt.Println("done")
}How it works
Count the function main as the entire surface area of Sync Cond Wait And Signal.
One loop does the cycling here: for !hasData. A goroutine takes the work off the current one. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Applying it
The demo output is labeled (consumer got:, done), so the printed output reads as a trace of the operations performed.
Statements that matter
dataReady := sync.NewCond(&mu)
var wg sync.WaitGroup
var mu sync.Mutex
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 Wait And Signal print when run?
- Execute the whole file; each printed line is prefixed with a label like `consumer got:`, `done`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.