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.

GoResilience

Code

gosnippet
39 lines
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

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`.