We'll take a look at a sample program where five threads push data to a shared Vec. The following program tries to do the same:
// thread_mut.rs
use std::thread;
use std::sync::Arc;
fn main() {
let mut nums = Arc::new(vec![]);
for n in 0..5 {
let mut ns = nums.clone();
thread::spawn(move || {
nums.push(n);
});
}
}
We have the same nums wrapped with Arc. But we cannot mutate it, as the compiler gives the following error:
This doesn't work as cloning Arc hands out immutable reference to the inner value. To mutate data from multiple threads, we need to use a type that provides shared mutability just like RefCell. But similar to Rc, RefCell cannot be used across multiple threads. Instead, we need to use their thread-safe variants such as the Mutex or RwLock wrapper types. Let's explore them next.