package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(4)
testCond()
}
func testCond() {
c := sync.NewCond(&sync.Mutex{})
condition := false
go func() {
time.Sleep(time.Second * 1)
c.L.Lock() //3 获得锁
fmt.Println("[1] 变更condition状态,并发出变更通知.")
condition = true
c.Signal() //c.Broadcast() //4 唤醒阻塞的main程,但是由于锁还没有释放,main抢不到锁会继续向下执行
time.Sleep(1 * time.Second)
fmt.Println("[1] 继续后续处理.")
c.L.Unlock() //5 释放锁,main抢到锁,接着执行
}()
c.L.Lock() //1 先获得锁
fmt.Println("[2] condition..........1")
for !condition {
fmt.Println("[2] condition..........2")
//等待Cond消息通知
c.Wait() //2 阻塞main,释放锁
fmt.Println("[2] condition..........3") //6 go程释放了锁 获得锁然后继续执行
}
fmt.Println("[2] condition..........4")
c.L.Unlock() //7解锁
time.Sleep(1 * time.Second)
fmt.Println("main end...")
}