Sub topic 16
Crossing threads: Arc and Mutex
This chapter assumes you know ownership and borrowing, have met Rc<T> and RefCell<T>, and understand traits and generics at a basic level. You should also know that std::thread::spawn runs a closure on a new thread.
Why Rc and RefCell stop at the thread boundary
Rc<T> and RefCell<T> are built for one thread. Rc<T> updates its reference count with plain, non-atomic reads and writes. If two threads cloned or dropped an Rc at the same moment, they could corrupt the count. That could free the value too early or never free it. RefCell<T> has the same problem with its borrow flag.
Rust does not leave this to your discipline. Two marker traits describe thread safety:
Send: a value of this type can be moved to another thread.Sync: a shared reference&Tcan be used from several threads. Equivalently,TisSyncwhen&TisSend.
The compiler implements these automatically for types made of Send and Sync parts. Rc<T> is neither Send nor Sync, so the compiler rejects any attempt to move one into a spawned thread.
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", data);
});
handle.join().unwrap();
}This program does not compile. The error says that Rc<i32> cannot be sent between threads safely. This is a compile-time failure, not a data race you find in production.
Arc: an atomic reference count
Arc<T> stands for atomically reference counted. It has the same API as Rc<T>: Arc::new, Arc::clone, Arc::strong_count, Arc::downgrade. The difference is that the count is updated with atomic operations, which are safe across threads. Arc<T> is Send and Sync when T is both Send and Sync.
Atomic operations cost more than plain increments. That is why Rc exists separately: in single-threaded code you should not pay for thread safety you do not use.
Here is the earlier example, fixed with Arc:
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(vec![1, 2, 3]);
let mut handles = Vec::new();
for i in 0..3 {
let data = Arc::clone(&data);
handles.push(thread::spawn(move || {
println!("thread {} sees {:?}", i, data);
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("strong count = {}", Arc::strong_count(&data));
}Each thread gets its own Arc handle, moved into the closure. The shared vector is freed when the last handle is dropped. After all threads are joined, the clones are gone, so the final count is 1. The order of the "thread" lines can vary between runs.
Note that Arc<T> gives only shared, read-only access, like Rc<T>. To mutate, you need something that provides interior mutability safely across threads.
Mutex: interior mutability with a lock
Mutex<T> (mutual exclusion) is the thread-safe counterpart to RefCell<T>. Where RefCell panics if you break the borrow rules, Mutex makes the second thread wait until the first is done.
You call lock() to get access. It returns a Result<MutexGuard<T>, PoisonError<...>>. The guard is a smart pointer: it implements Deref and DerefMut so you can use it like &mut T, and it implements Drop so the lock is released when the guard goes out of scope. You never call "unlock" yourself.
use std::sync::Mutex;
fn main() {
let counter = Mutex::new(0);
{
let mut guard = counter.lock().unwrap();
*guard += 1;
} // guard dropped here, lock released
println!("counter = {:?}", counter);
}The inner block matters. If you kept guard alive, a second lock() on the same thread could block forever or panic.
Arc and Mutex together
Arc<Mutex<T>> is the thread-safe version of Rc<RefCell<T>>. Arc provides shared ownership, and Mutex provides controlled mutation.
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..8 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
let mut guard = counter.lock().unwrap();
*guard += 1;
}
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("total = {}", *counter.lock().unwrap());
}This prints total = 8000 on every run. Eight threads each add 1000 times, and the mutex ensures no increment is lost. Without the lock, increments could overwrite each other and the total would be unpredictable.
| Single-threaded | Thread-safe | What changes |
|---|---|---|
| `Rc<T>` | `Arc<T>` | Atomic reference count, slightly slower |
| `RefCell<T>` | `Mutex<T>` | Waits for the lock instead of panicking |
| `RefCell<T>` (read-heavy) | `RwLock<T>` | Many readers or one writer |
Common errors and gotchas
- Forgetting
move. A spawned closure may outlive the current function, so it cannot borrow local variables. Usemoveand give each thread its ownArcclone. - Moving the original
Arcin a loop. If the closure movescounteritself, the second iteration fails with "value moved in previous iteration." Clone inside the loop and shadow the name, as in the examples. - Holding a guard too long. The lock is held until the guard is dropped. Long work under a lock serializes your threads. Keep the guarded scope small, or call
drop(guard)early. - Deadlock. Two threads that each hold one lock and wait for the other's will wait forever. Rust does not detect this. A common defense is to always acquire multiple locks in the same order.
- Poisoning. If a thread panics while holding a guard, the mutex is marked poisoned, and later
lock()calls returnErr. Callingunwrap()then panics too, which is often the right default. You can recover the data withPoisonError::into_innerif you can tolerate possibly inconsistent state. - Reference cycles still leak.
Arccycles leak just likeRccycles. UseWeakfromstd::syncto break them. Arc<T>does not makeTthread-safe.Arc<RefCell<i32>>does not compile across threads, becauseRefCellis notSync.
Summary of the decision
Use Rc<RefCell<T>> when everything stays on one thread. Use Arc<Mutex<T>> when data must be shared and changed across threads. If the data is read-only after setup, plain Arc<T> is enough and avoids locking entirely.
Exercise
A teammate writes let shared = Arc::new(RefCell::new(0)); and passes clones to several spawned threads. Why does this fail to compile, and what is the minimal change that fixes it?
Show answer
RefCell<i32> is not Sync, so Arc<RefCell<i32>> is not Send, and the compiler refuses to move it into a thread. Replace RefCell with Mutex, giving Arc<Mutex<i32>>, and access the value through lock().unwrap().
Exercise
In the eight-thread counter example, what happens to the final total if you hold the guard for the whole inner loop (taking the lock once, outside the for _ in 0..1000 loop)? Is the result still correct, and what changes?
Show answer
The total is still 8000, because the lock still guards every increment. The threads now run their loops one after another instead of interleaving lock acquisitions, which reduces lock contention overhead but also removes any parallelism. For work this small, that is fine. For real work done under the lock, it would serialize the threads.