https://asong.cloud/go%E5%AE%9E%E7%8E%B0%E5%8F%AF%E9%87%8D%E5%85%A5%E9%94%81/
1 基本用法
Go标准库提供了Cond原语,为等待/通知场景下的并发问题提供支持。
Cond可以让一组的Goroutine都在满足特定条件时被唤醒,在条件还没有满足的时候,所有等待这个条件的goroutine都会被阻塞住,只有这一组goroutine通过协作达到了这个条件,等待的goroutine才可以继续进行下去。 ```go package main
import ( “fmt” “sync” “time” )
var ( done = false topic = “A” )
func main() { cond := sync.NewCond(&sync.Mutex{}) go Consumer(topic, cond) go Consumer(topic, cond) go Consumer(topic, cond) Push(topic, cond) time.Sleep(5 * time.Second)
}
func Consumer(topic string, cond *sync.Cond) { cond.L.Lock() for !done { cond.Wait() } fmt.Println(“topic is “, topic, “ starts Consumer”) cond.L.Unlock() }
func Push(topic string, cond *sync.Cond) { fmt.Println(topic, “starts Push”) cond.L.Lock() done = true cond.L.Unlock() fmt.Println(“topic is “, topic, “ wakes all”) cond.Broadcast() } ```