当一个阻止goroutine的RWMutex解锁时会被唤醒

时间:2016-05-26 02:22:56

标签: go concurrency mutex

var mu sync.RWMutex

//goroutine 1
go func() {
    mu.Lock()
    defer mu.Unlock()
   //something else
}()
//goroutine 2
go func() {
    mu.Lock()
    defer mu.Unlock()
    //something else
}()
//goroutine 3
go func() {
    mu.RLock()
    defer mu.RUnlock()
    //something else
}()
//goroutine 4
go func() {
    mu.RLock()
    defer mu.RUnlock()
    //something else
}()

goroutine 1现在获得锁定,goroutine 2,3,4被阻止。 当goroutine 1释放锁定时,goroutine会先被唤醒吗?随机?

1 个答案:

答案 0 :(得分:2)

为了确保锁定最终可供作者使用,被阻止的Lock调用会阻止新读者获取锁定。如果在Lock上goroutine 3之前goroutine 2在RLock上阻塞,则goroutine 2将在goroutine 3之前运行。如果goroutine 3在goroutine 2阻塞之前在RLock上阻塞,则执行顺序未指定Lock