How to correctly use sync.Cond?

前端 未结 8 803
忘了有多久
忘了有多久 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:16

    You need to make sure that c.Broadcast is called after your call to c.Wait. The correct version of your program would be:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        m := &sync.Mutex{}
        c := sync.NewCond(m)
        m.Lock()
        go func() {
            m.Lock() // Wait for c.Wait()
            c.Broadcast()
            m.Unlock()
        }()
        c.Wait() // Unlocks m, waits, then locks m again
        m.Unlock()
    }
    

    https://play.golang.org/p/O1r8v8yW6h

提交回复
热议问题