douxie7738 2019-08-13 09:09 采纳率: 0%
浏览 59
已采纳

如果写操作在设计上从未相互竞争,使用sync.RWMutex的读锁进行写操作并使用其写锁进行读操作是否安全?

From the Go docs:

A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer.

This introductory sentence is never followed by a definition of what a reader and writer may and may not do. Thus, I wonder whether a certain stretch of the definition is possible.

Suppose we have a set of many goroutines; let's call it S. Each of the goroutines in S has its own resources which it reads from and writes to frequently. Suppose I have one extra goroutine R which routinely wants to scrape the state of the resources written by the goroutines in S. Let's explore the two more obvious solutions to see where I am going.

  1. We can use a single mutex. However, the goroutines in S would needlessly compete for the lock, since each goroutine from S accesses only its own resources anyway.
  2. Use one mutex for each goroutine in S. This eliminates needless competition and even gives R the option to decide whether it needs to have locked all mutexex at once or merely each mutex at least once at some point in time. Requires some extra work however.

So my third idea is this: Let the goroutines in S take the read lock of a sync.RWMutex when they want to read or write (i.e. a generalized inclusive lock) and let R take the write lock of that mutex when it wants to read (i.e. a generalized exclusive lock). In other words:

Is it safe to use the read lock of sync.RWMutex for writing and its write lock for reading if the writes never race with each other by design?

  • 写回答

2条回答 默认 最新

  • douding6266 2019-08-13 09:56
    关注

    The answer of your question is Yes, just like Volker said.

    I would give you a more idiomatic Go solution:

    every resources of goroutines in S take a sync.RWMutex
    the goroutines in S read after sync.RWMutex.Rlock()
    the goroutines in S write after sync.RWMutex.Lock()
    extra goroutine R read after sync.RWMutex.Rlock()
    

    I think you just go into the wrong region, it should be a simple problem. :)

    If I misunderstand you, tell me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测