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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等