Mutex and RwLock are synchronization primitives in Rust that facilitate safe concurrent access to shared resources however, they differ in how they handle shared data access.
A Mutex (short for mutual exclusion) is an exclusive locking mechanism that allows only one thread to acquire a lock at a time. The thread that successfully acquires the lock gains access to the locked data, but all other threads that try to acquire the lock are blocked until the lock is released. Mutexes are great for use cases where we need to guarantee that only one thread has access to the data at any given time.
Here is an example use of a Mutex:
use std::sync::Mutex;
// sharing a counter across threads using a Mutex
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let handle = std::thread::spawn({
let counter = counter.clone();
move || {
let mut num = counter.lock().unwrap();
*num += 1;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {:?}", *counter.lock().unwrap());
}
On the other hand, RwLock (short for reader-writer lock) is a synchronization mechanism that allows multiple threads to acquire a shared lock at once and only one thread to acquire an exclusive lock. RwLock is perfect for scenarios where data is frequently read but infrequently written.
Here is an example use of RwLock:
use std::sync::RwLock;
fn main() {
let shared_data = RwLock::new(vec![1, 2, 3]);
// Read threads can run simultaneously
for _ in 0..3 {
let shared_data = shared_data.clone();
std::thread::spawn(move || {
let val = shared_data.read().unwrap().clone();
println!("Read {:?}", val);
});
}
// Only one write thread is allowed at a time
let shared_data = shared_data.clone();
std::thread::spawn(move || {
let mut data = shared_data.write().unwrap();
data.push(4);
println!("Write {:?}", data);
}).join().unwrap();
}
In conclusion, Mutex is best used when there is a need for exclusive access to a shared resource, while RwLock is best used when there is a need for both shared read access and exclusive write access to the same shared resource.