Golang读写锁读锁重复获取的问题

遇到Golang的sync.RWMutex的一个坑,同一个协程重复获取读锁导致的死锁为题。

代码如下

var (
    l sync.RWMutex
)

func f1() {
    l.RLock()
    defer l.RUnlock()
    f2()
    // ...
}

func f2() {
    l.RLock()
    defer l.RUnlock()
    // ...
}

大概就是,一个函数里面获取读锁,然后调用另一个函数,另一个函数也去获取读锁,然后还有其他协程获取写锁。结果就出现死锁了。

godoc的说明如下:

If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released. In particular, this prohibits recursive read locking. This is to ensure that the lock eventually becomes available; a blocked Lock call excludes new readers from acquiring the lock.

大意就是,写锁优先级更高,一旦有了写锁的请求,新来的读锁的请求都得排在后面。

于是就会出现这个时序:

1、f1获取到了读锁

2、在调用f2之前其他协程申请写锁

3、f2的读锁请求排在了写锁请求之后

于是死锁了

 

你可能感兴趣的:(Golang)