Go cond锁定期唤醒锁


package main

import (
    "fmt"
    "sync"
    "time"
)

var locker = new(sync.Mutex)
var cond = sync.NewCond(locker)

func test(x int) {
    // 获取锁
    cond.L.Lock()
    // 等待通知  暂时阻塞
    cond.Wait()
    fmt.Println(x)
    time.Sleep(time.Second * 1)
    // 释放锁
    cond.L.Unlock()
}
func main() {
    for i := 0; i < 40; i++ {
        go test(i)
    }
    fmt.Println("start all")
    time.Sleep(time.Second * 3)
    fmt.Println("broadcast")
    // 下发一个通知给已经获取锁的goroutine
    cond.Signal()
    time.Sleep(time.Second * 3)
    // 3秒之后 下发一个通知给已经获取锁的goroutine
    cond.Signal()
    time.Sleep(time.Second * 3)
    // 3秒之后 下发广播给所有等待的goroutine
    cond.Broadcast()
    time.Sleep(time.Second * 60)
}
分享:

评论