Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
Boiethios Avatar asked Jun 05 '18 15:06

Boiethios


People also ask

When would you use a mutex lock?

Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time.

Is RwLock faster than mutex?

In the process I wanted to test how my work performed compared to a standard library RwLock and Mutex. On my home laptop the RwLock was 5 times faster, the Mutex 2 times faster than my work. So checking out my code on my workplace workstation and running my bench marks I noticed the Mutex was the same - 2 times faster.

Is RwLock thread safe?

Sender<T> is not Sync meaning that RwLock<Sender<T>> is not Sync , meaning that Arc<RwLock<Sender<T>>> is neither Send nor Sync . That means that this type, despite containing three different supposedly thread safe synchronization types is not thread safe at all.


1 Answers

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.

like image 162
Boiethios Avatar answered Sep 20 '22 12:09

Boiethios