Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goroutine blocks when calling RWMutex RLock twice after an RWMutex Unlock

var mu sync.RWMutex

go func() {
    mu.RLock()
    defer mu.RUnlock()

    mu.RLock()  // In my real scenario this second lock happened in a nested function.
    defer mu.RUnlock()

    // More code.
}()

mu.Lock()
mu.Unlock()  // The goroutine above still hangs.

If a function read-locks a read/write mutex twice, while another function write-locks and then write-unlocks that same mutex, the original function still hangs.

Why is that? Is it because there's a serial order in which mutexes allow code to execute?

I've just solved a scenario like this (which took me hours to pinpoint) by removing the second mu.RLock() line.

like image 588
Ory Band Avatar asked Dec 24 '22 18:12

Ory Band


1 Answers

This is one of several standard behaviours for a read-write lock. What Wikipedia calls "Write-preferring RW locks".

The documentation for sync's RWMutex.Lock says:

To ensure that the lock eventually becomes available, a blocked Lock call excludes new readers from acquiring the lock.

Otherwise a series of readers that each acquired the read lock before the previous released it could starve out writes indefinitely.

This means that it is always unsafe to call RLock on a RWMutex that the same goroutine already has read locked. (Which by the way is also true of Lock on regular mutexes as well, as Go's mutexes do not support recursive locking.)

The reason it is unsafe is that if the goroutine ever blocks getting the second read lock (due to a blocked writer) it will never release the first read lock. This will cause every future lock call on the mutex to block forever, deadlocking part or all of the program. Go will only detect a deadlock if all goroutines are blocked.

like image 131
Dave C Avatar answered May 06 '23 07:05

Dave C