常用方法:

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发送信息

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. func main() {
  8. locker := new(sync.Mutex)
  9. cond := sync.NewCond(locker)
  10. for i := 0 ; i < 30 ; i++ {
  11. go func(x int) {
  12. cond.L.Lock()
  13. fmt.Println(x," 获取锁")
  14. defer cond.L.Unlock()
  15. cond.Wait()
  16. fmt.Println(x," 被唤醒")
  17. }(i)
  18. }
  19. time.Sleep(time.Second)
  20. fmt.Println("Signal...")
  21. cond.Signal()
  22. time.Sleep(time.Second)
  23. cond.Signal()
  24. time.Sleep(time.Second*3)
  25. fmt.Println("Broadcast...")
  26. cond.Broadcast()
  27. time.Sleep(time.Second * 30)
  28. }

参考:

https://blog.csdn.net/skh2015java/article/details/102730802