A sync.Cond
only makes use of the methods required by a sync.Locker: Lock
and Unlock
. The minimal interface needed by Cond
is therefore just those two methods.
You can still use your RWMutex
directly (as opposed to going through Cond
), and Cond
will still work.
func main() {
myMutex := &sync.RWMutex{}
cond := sync.NewCond(myMutex)
// Use the RW mutex directly.
myMutex.RLock()
myMutex.RUnlock()
// Use the mutex through cond. Lock and Unlock only.
cond.L.Lock()
cond.L.Unlock()
}
Or you can use it through Cond.L
after making sure it is of the expected type:
func main() {
cond := &sync.Cond{L: &sync.RWMutex{}}
// Typecheck cond.L.
myRWMutex, ok := cond.L.(*sync.RWMutex)
if !ok {
panic("AHHHH!!!")
}
myRWMutex.RLock()
myRWMutex.RUnlock()
}
(you can skip the type check and just say cond.L.(*sync.RWMutex)
but if it isn't a sync.RWMutex
, your program will panic)