dongzong7467 2015-05-30 15:27
浏览 102
已采纳

在RWMutex解锁后两次调用RWMutex RLock时,goroutine会阻塞

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.

  • 写回答

1条回答 默认 最新

  • douzi1350 2015-05-30 17:25
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用