In Rust's concurrent programming model, Mutex and RwLock are essential synchronization primitives. They ensure safe access to shared data across multiple threads, preventing race conditions and data corruption.
A Mutex allows only one thread to access the data at a time. It's ideal for scenarios where you need exclusive access to a resource.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
In this example, we use a Mutex to safely increment a counter across multiple threads.
An RwLock allows multiple readers or a single writer to access the data. It's useful when you have data that is frequently read but infrequently modified.
use std::sync::{Arc, RwLock};
use std::thread;
fn main() {
let data = Arc::new(RwLock::new(vec![1, 2, 3]));
let mut handles = vec![];
// Reader threads
for _ in 0..3 {
let data = Arc::clone(&data);
handles.push(thread::spawn(move || {
let numbers = data.read().unwrap();
println!("Read: {:?}", *numbers);
}));
}
// Writer thread
{
let data = Arc::clone(&data);
handles.push(thread::spawn(move || {
let mut numbers = data.write().unwrap();
numbers.push(4);
println!("Write: {:?}", *numbers);
}));
}
for handle in handles {
handle.join().unwrap();
}
}
This example demonstrates how RwLock allows multiple reader threads to access the data concurrently, while ensuring exclusive access for the writer thread.
Mutex when you need exclusive access to data.RwLock when you have mostly read operations and occasional writes.Arc (Atomic Reference Counting) to share ownership across threads.To fully understand Mutex and RwLock in Rust, it's helpful to explore these related topics:
By mastering these synchronization primitives, you'll be well-equipped to write safe and efficient concurrent Rust programs.