When or why should I use a Mutex over an RwLock?

有些话、适合烂在心里 提交于 2019-11-30 01:37:03

问题


When I read the documentations of Mutex and RwLock, the difference I see is the following:

  • Mutex can have only one reader or writer at a time,
  • RwLock can have one writer or multiple reader at a time.

When you put it that way, RwLock seems always better (less limited) than Mutex, why would I use it, then?


回答1:


Sometimes it is better to use a Mutex over an RwLock in Rust:

RwLock<T> needs more bounds for T to be thread-safe:

  • Mutex requires T: Send to be Sync,
  • RwLock requires T to be Send and Sync to be itself Sync.

In other words, Mutex is the only wrapper that can make a T syncable. I found a good and intuitive explanation in reddit:

Because of those bounds, RwLock requires its contents to be Sync, i.e. it's safe for two threads to have a &ptr to that type at the same time. Mutex only requires the data to be Send, because conceptually you can think of it like when you lock the Mutex it sends the data to your thread, and when you unlock it the data gets sent to another thread.

Use Mutex when your T is only Send and not Sync.

Preventing writer starvation

RwLock does not have a specified implementation because it uses the implementation of the system. Some read-write locks can be subject to writer starvation while Mutex cannot have this kind of issue.

Mutex should be used when you have possibly too many readers to let the writers have the lock.



来源:https://stackoverflow.com/questions/50704279/when-or-why-should-i-use-a-mutex-over-an-rwlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!