Mutex and RwLock are both similar to RefCell in some ways, but not as closely related as Arc is to Rc.
It's Mutex's job to make sure that only one thread has access to the contained data at a time. Since it guarantees that only one block of code has access at all at any given time, a Mutex can safely provide both read and write access without breaking Rust's rules.
In the following example, we have Mutex and Arc in action, and some very basic multithreading:
let counter = Arc::new(Mutex::new(0));
for _ in 0..10 {
let local_counter = Arc::clone(&counter);
thread::spawn(move || {
let wait = time::Duration::new(random::<u64>() % 8, 0);
thread::sleep(wait);
let mut shared = local_counter.lock().unwrap();
*shared += 1;
});
}
loop {
{
let shared = counter.lock().unwrap();
println!("{} threads have completed", *shared...