常用方法:
func(c Cond)Wait()
*必须获取该锁之后才能调用Wait()方法,Wait方法在调用时会释放底层锁Locker,并且将当前goroutine挂起,直到另一个goroutine执行Signal或者Broadcase,该goroutine才有机会重新唤醒,并尝试获取Locker,完成后续逻辑。
也就是在等待被唤醒的过程中是不占用锁Locker的,这样就可以有多个goroutine可以同时处于Wait
func(c *Cond)Signal()
发现等待时间最长的的goroutine并通知它
func(c *Cond)Broadcast()
向所有等待的goroutine发送信息
package main
import (
"fmt"
"sync"
"time"
)
func main() {
locker := new(sync.Mutex)
cond := sync.NewCond(locker)
for i := 0 ; i < 30 ; i++ {
go func(x int) {
cond.L.Lock()
fmt.Println(x," 获取锁")
defer cond.L.Unlock()
cond.Wait()
fmt.Println(x," 被唤醒")
}(i)
}
time.Sleep(time.Second)
fmt.Println("Signal...")
cond.Signal()
time.Sleep(time.Second)
cond.Signal()
time.Sleep(time.Second*3)
fmt.Println("Broadcast...")
cond.Broadcast()
time.Sleep(time.Second * 30)
}