Sub topic 16
Crossing threads: Arc and Mutex
This chapter assumes you know Rc<T>, RefCell<T>, and the basics of spawning threads with std::thread. It shows the thread-safe counterparts of those two types.
Why Rc and RefCell stop at one thread
Rc<T> updates its reference count with ordinary arithmetic. If two threads clone or drop an Rc at the same moment, the count can be corrupted. Rust prevents this at compile time. Rc<T> does not implement the Send trait, which marks types that are safe to move to another thread. RefCell<T> does not implement Sync, which marks types that are safe to share by reference between threads.
The thread-safe pairs are:
| Single-threaded | Thread-safe | What changes |
|---|---|---|
| `Rc<T>` | `Arc<T>` | The count uses atomic operations |
| `RefCell<T>` | `Mutex<T>` | Access is guarded by a lock, not a borrow flag |
Arc: atomic reference counting
Arc<T> (atomically reference counted) has the same API as Rc<T>: Arc::clone, Arc::strong_count, and Arc::downgrade. The atomic count costs a little more than Rc, so use Rc when you stay on one thread.
Mutex: one thread at a time
Mutex<T> (mutual exclusion) owns a value and lets one thread access it at a time. You call lock(), which waits until the lock is free. It returns a Result holding a guard of type MutexGuard<T>. The guard implements Deref and DerefMut, so you use it like a reference. It also implements Drop, so the lock is released when the guard goes out of scope.
Like RefCell, Mutex gives interior mutability. The difference is how it handles a conflict. RefCell panics. Mutex makes the second thread wait.
Arc<Mutex<T>>: the threaded Rc<RefCell<T>>
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
*counter.lock().unwrap() += 1;
}
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("total = {}", *counter.lock().unwrap());
}The program prints total = 4000. Each thread gets its own Arc clone, moved into the closure. All clones point to one Mutex<i32>. The guard from lock() is a temporary, so the lock is released at the end of each increment statement.
Common errors
- Using
Rcinthread::spawn. The compiler rejects it with an error sayingRc<...>cannot be sent between threads safely. Switch toArc. - Using
Arc<T>alone and expecting to mutate.Arcgives shared, read-only access, just likeRc. Wrap the value inMutex. - Holding a guard too long. Other threads wait for as long as the guard lives. Keep the critical section short, or end the guard's scope early with a block.
- Locking two mutexes in opposite orders in different threads. This can cause a deadlock, where each thread waits for the other. Rust does not prevent it.
Exercise
Your program wraps a Vec<i32> in Rc<RefCell<Vec<i32>>> and the compiler rejects passing a clone into thread::spawn. Which type should replace Rc<RefCell<...>>, and why?
Show answer
Use Arc<Mutex<Vec<i32>>>. Rc and RefCell are not thread-safe, so they do not implement Send and Sync. Arc counts owners atomically, and Mutex ensures only one thread accesses the vector at a time.