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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)