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 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染