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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64