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 now get the lock, goroutine 2,3,4 blocked. when goroutine 1 release the lock, which goroutine will be waked up first? Randomly?
To ensure that locks eventually becomes available to writers, a blocked Lock
call excludes new readers from acquiring the lock. If goroutine 2 blocks on Lock
before goroutine 3 blocks on RLock
, then goroutine 2 will run before goroutine 3. The execution order is unspecified if goroutine 3 blocks on RLock
before goroutine 2 blocks on Lock
.