[Day13] Read Rust Atomics and Locks - More about Reader-Writer Lock
by Mara Bos
From: Reader-Writer Lock
To: Mutexes in Other Languages
At Topics: Chapter 1. Basics of Rust Concurrency
Recall
- Trait
Send
: A type isSend
if it can be sent to another thread. In other words, if ownership of a value of that type can be transferred to another thread. - Trait
Sync
: A type isSync
if it can be shared with another thread. In other words, a typeT
isSync
if and only if a shared reference to that type&T
isSend
.
Notes
Reader-Writer Lock
A mutex is only concerned with exclusive access. The MutexGuard
will always provide us an exclusive reference (&mut T) to the protected data, even if we only wanted to look at the data and and a shared reference (&T) would have been enough.
A reader-writer understands the difference between exclusive and shared access, and can provide either.
A reader-writer has tree states:
- Unlocked
- Locked by a single writer (for exclusive access)
- Locked by any number of readers (for shared access)
When to use it?
It is commonly used for data that is often read by multiple threads, but only updated once in a while.
Rust's Reader-Writer Lock
std::sync::RwLock<T>
- Instead of a
lock()
, it has aread()
and awrite()
method - Two guard types:
RwLockReadGuard
(for readers),RwLockWriteGuard
(for writers) - Both
Mutex<T>
andRwLock<T>
requireT
to beSend
(able be used to send aT
to another thread) RwLock<T>
'sT
is alsoSync
- The Rust standard library provides only one general purpose
RwLock
type, but its implementation depends on the OS
Mutexes in Rust vs Other Languages
- Rust’s
Mutex<T>
contains the data it is protecting. However, in C++, for example,std::mutex
does not contain the data it protects, nor does it even know what it is protecting.