How to correctly use sync.Cond?

前端 未结 8 797
忘了有多久
忘了有多久 2021-02-01 16:11

I\'m having trouble figuring out how to correctly use sync.Cond. From what I can tell, a race condition exists between locking the Locker and invoking the condition\'s Wait meth

8条回答
  •  醉梦人生
    2021-02-01 17:06

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        m := sync.Mutex{}
        m.Lock() // main gouroutine is owner of lock
        c := sync.NewCond(&m)
        go func() {
            m.Lock() // obtain a lock
            defer m.Unlock()
            fmt.Println("3. goroutine is owner of lock")
            time.Sleep(2 * time.Second) // long computing - because you are the owner, you can change state variable(s)
            c.Broadcast()               // State has been changed, publish it to waiting goroutines
            fmt.Println("4. goroutine will release lock soon (deffered Unlock")
        }()
        fmt.Println("1. main goroutine is owner of lock")
        time.Sleep(1 * time.Second) // initialization
        fmt.Println("2. main goroutine is still lockek")
        c.Wait() // Wait temporarily release a mutex during wating and give opportunity to other goroutines to change the state.
        // Because you don't know, whether this is state, that you are waiting for, is usually called in loop.
        m.Unlock()
        fmt.Println("Done")
    }
    

    http://play.golang.org/p/fBBwoL7_pm

提交回复
热议问题