Sub topic 18
Arc and Mutex: ownership across threads
This chapter assumes you know moves, borrowing, Rc, and RefCell from the earlier chapters. It also assumes you can spawn a thread with std::thread::spawn. You will see why Rc<RefCell<T>> cannot cross threads, what Arc<Mutex<T>> changes, and which mistakes to expect.
Why threads change the rules
thread::spawn takes a closure that may outlive the function that created it. The compiler therefore requires the closure to own everything it uses, or to borrow only 'static data. A reference to a local variable fails this requirement. A thread can also run in parallel with other code, so two threads could mutate the same value at once. That is a data race, and Rust rejects it at compile time.
Two marker traits carry the rule:
Send: a value of this type can be moved to another thread.Sync: a type isSyncwhen&TisSend. In other words, shared references to it may be used from several threads.
You never implement these by hand. The compiler derives them from a type's fields.
Why Rc fails
Rc updates its reference count with plain, non-atomic arithmetic. Two threads cloning at once could corrupt the count, which could free memory too early or never. So Rc<T> is not Send.
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
// Uncommenting the next three lines fails to compile:
// error[E0277]: `Rc<i32>` cannot be sent between threads safely
// let h = thread::spawn(move || println!("{data}"));
// h.join().unwrap();
println!("{data}");
let _ = thread::current();
}The error message names the cause. It says the trait Send is not implemented for Rc<i32>. Read this as a request to switch to a thread-safe type, not as a bug in your logic.
Arc: atomic reference counting
Arc<T> (atomically reference counted) has the same API as Rc<T>. Arc::clone increments the count with atomic CPU instructions, so concurrent clones and drops are safe. The value is freed when the last Arc is dropped, on whichever thread that happens.
| Type | Count updates | `Send` / `Sync` | Cost |
|---|---|---|---|
| `Rc<T>` | Plain | Neither | Cheapest |
| `Arc<T>` | Atomic | Yes, if `T` is `Send + Sync` | Slightly slower clone and drop |
Arc<T> gives shared ownership but only shared access, the same as Rc<T>. You cannot get &mut T out of it while other owners exist. For mutation you need a lock.
Mutex: one thread at a time
Mutex<T> (mutual exclusion) owns a value and hands out access only through lock(). This is the thread-safe counterpart of RefCell. RefCell panics when its rules are broken, while Mutex makes the second thread wait.
| Row | `RefCell<T>` | `Mutex<T>` |
|---|---|---|
| Threads | One | Many |
| Conflict | Panics | Blocks until free |
| Access | `borrow()`, `borrow_mut()` | `lock()` |
| Release | Guard dropped | Guard dropped |
lock() returns Result<MutexGuard<T>, PoisonError<...>>. The guard derefs to T. When the guard is dropped, the lock is released. That is ownership again: the lock lives exactly as long as a value.
The standard pattern
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. Each iteration creates a new Arc handle named c and moves it into the thread. The original counter stays in main. Without the clone, the first move closure would take counter and the second iteration would fail with "use of moved value".
Guard lifetime and lock scope
A guard keeps the lock until it is dropped. In *c.lock().unwrap() += 1; the guard is a temporary, so it drops at the end of that statement. If you bind it with let, it lives to the end of the enclosing block. Keep that block short, because other threads wait the whole time.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let log = Arc::new(Mutex::new(Vec::new()));
let handles: Vec<_> = (0..3)
.map(|id| {
let log = Arc::clone(&log);
thread::spawn(move || {
let mut guard = log.lock().unwrap();
guard.push(id);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
let mut result = log.lock().unwrap().clone();
result.sort();
println!("{:?}", result);
}This prints [0, 1, 2]. Thread order varies between runs, so the program sorts before printing. If you need to do slow work, such as reading a file or sleeping, do it before lock() or after the guard is dropped. You can end a guard early with drop(guard).
Common errors
- Closure may outlive the function. You borrowed a local variable in
thread::spawn. Addmoveand clone theArcfirst. - Use of moved value in a loop. You moved the
Arcitself into the first closure. Clone inside the loop, beforespawn. Rc<...>cannot be sent between threads safely. ReplaceRcwithArcandRefCellwithMutex.- Deadlock. Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1. Calling
lock()twice on the same mutex in one thread can also hang or panic. Rust does not detect deadlocks. Acquire multiple locks in one fixed order, and hold each for as short a time as possible. - Ignoring errors from
lock().unwrap()is common, but it turns a poisoned mutex into a panic. The next section explains why.
Poisoning
If a thread panics while holding a guard, the mutex becomes poisoned. Later lock() calls return Err, because the protected data may be half-updated. You can still recover the data from the error.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let m = Arc::new(Mutex::new(0));
let m2 = Arc::clone(&m);
let result = thread::spawn(move || {
let _guard = m2.lock().unwrap();
panic!("boom");
})
.join();
println!("thread failed: {}", result.is_err());
match m.lock() {
Ok(guard) => println!("fine {}", *guard),
Err(poisoned) => {
let guard = poisoned.into_inner();
println!("recovered {}", *guard);
}
}
}The program prints a panic message on stderr, then thread failed: true and recovered 0. Recover only if you can check or repair the data. Otherwise, propagating the panic with unwrap() is a reasonable choice.
Choosing the right tool
- Read-only data shared by many threads needs only
Arc<T>, with no lock. - Many readers and few writers suit
Arc<RwLock<T>>. It allows many simultaneous readers or one writer, the same rule as&Tand&mut T, enforced at run time. - A single integer counter or flag is cheaper with
AtomicUsizeorAtomicBool. - If threads only need to borrow local data and finish before the function returns, use
thread::scope. It needs noArcand nomove.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let total = thread::scope(|s| {
let h = s.spawn(|| data.iter().sum::<i32>());
h.join().unwrap()
});
println!("{total} from {} items", data.len());
}This prints 6 from 3 items. Scoped threads are guaranteed to end before scope returns, so borrowing data is safe.
Gotchas
Arc<Mutex<T>>protects each access. It does not protect a sequence of accesses. If you read, release the lock, and write back, another thread can change the value in between. Do the whole update under one guard.Arccycles leak, just asRccycles do. UseWeakfor back-pointers.Arc<T>requiresT: Send + Syncto be sent.Mutex<T>isSyncwhenTisSend, which is whyArc<Mutex<Cell<i32>>>works butArc<RefCell<i32>>does not.
Exercise
This loop fails with "use of moved value: counter" on the second iteration. Why, and what is the fix?
let counter = Arc::new(Mutex::new(0));
for _ in 0..3 {
thread::spawn(move || {
*counter.lock().unwrap() += 1;
});
}
Show answer
The move closure takes ownership of counter itself in the first iteration, so it is gone for the second. Create a new handle in each iteration with let c = Arc::clone(&counter); before thread::spawn, and use c inside the closure. Keep the JoinHandle values and call join() if you need the threads to finish before reading the result.
Exercise
A worker thread panics while holding a MutexGuard. What does the next call to lock() return, and how can the program still read the data?
Show answer
It returns Err(PoisonError), because the mutex is poisoned. The program can call into_inner() on the error to get the guard and read the data. It should do this only if the data is still valid or can be checked.