Sub topic 18
Arc and Mutex: ownership across threads
This chapter assumes you know moves, Rc, and RefCell from the earlier chapters, and that you have spawned a thread with std::thread::spawn before.
Why Rc is not enough
A spawned thread may outlive the function that created it, so its closure must own everything it uses. You can't hand a plain reference to it. Several threads sharing one value need shared ownership, which is what Rc gives you in a single thread.
Rc fails across threads because its reference count is updated without synchronization. Two threads could update it at once and corrupt the count. The compiler stops this with two marker traits:
Sendmeans a value can be moved to another thread.Syncmeans a shared reference to the value can be used from several threads.
Rc<T> implements neither, so thread::spawn rejects it at compile time.
Arc: an atomic Rc
Arc<T> (atomically reference counted) has the same interface as Rc<T>. It uses atomic operations for the count, which costs slightly more. Use Rc in single-threaded code and Arc when the value crosses threads.
Arc<T> only hands out shared references, as Rc does. To change the data you need interior mutability that is safe across threads. Mutex<T> provides it.
Mutex: one writer at a time
A Mutex<T> (mutual exclusion lock) owns a value of type T. To reach the value you call lock(), which blocks until the lock is free and returns a guard wrapped in a Result. The guard dereferences to T. When the guard is dropped, the lock is released. This is the same drop-at-end-of-scope rule from earlier in the tutorial.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..4 {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*c.lock().unwrap() += 1;
}));
}
for h in handles {
h.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}This prints 4. Step by step:
Arc::new(Mutex::new(0))puts the counter on the heap with one owner.Arc::clone(&counter)adds an owner and copies only the pointer, not the number.movetransfers that clone into the thread's closure.lock().unwrap()waits for the lock. The guard is a temporary, so it is dropped at the end of the statement.join()waits for each thread. The main thread then locks the counter and reads the total.
Common errors
Rc<T>cannot be sent between threads safely. ReplaceRcwithArc.- Closure may outlive the current function. Add
moveand clone theArcbefore the closure, once per thread. - Using the original after
move. Clone first, as the loop above does, and keep the originalArcfor the main thread. - Holding a guard too long. Other threads wait the whole time the guard is alive. Keep the locked region small, using a block if needed.
- Deadlock. Locking the same
Mutextwice in one thread, or two mutexes in opposite orders in two threads, can block forever. The compiler can't catch this.
Exercise
A teammate writes let data = Arc::new(vec![1, 2, 3]);, spawns threads that each call data.push(4), and gets a compile error. What is wrong, and what is the fix?
Show answer
Arc gives only shared references, and push needs &mut Vec. Wrap the vector in a mutex: Arc::new(Mutex::new(vec![1, 2, 3])). Each thread then calls data.lock().unwrap().push(4) on its own Arc::clone.