Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...