duanlu4371 2018-02-19 07:04
浏览 97
已采纳

使用RWMutex代替Mutex有什么好处?

I am not sure when to use RWMutex and when to use Mutex.

Do you save resources if you use RWMutex instead of Mutex if you do more reads then writes?

I see some people use Mutex all the time no matter what they do, and some use RWMutex and run these methods:

func (rw *RWMutex) Lock()
func (rw *RWMutex) Unlock()
func (rw *RWMutex) RLock()
func (rw *RWMutex) RUnlock()

instead of just:

func (m *Mutex) Lock()
func (m *Mutex) Unlock()

If you save resources, is it that much of a difference that you should use RWMutex if you do more reads then writes?

  • 写回答

2条回答 默认 最新

  • dsavz66262 2018-02-19 07:08
    关注

    From the docs (emphasize mine):

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

    In other words, readers don't have to wait for each other. They only have to wait for writers holding the lock.

    A sync.RWMutex is thus preferable for data that is mostly read, and the resource that is saves compared to a sync.Mutex is time.

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

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: