Sub topic 10
Arc<Mutex<T>> and the bounds it needs
This chapter assumes you know ownership and borrowing, trait bounds, move closures, and basic use of thread::spawn and JoinHandle. You should also know what Send and Sync each promise. Send means a value can move to another thread. Sync means &T can be shared with another thread.
Arc<Mutex<T>> is the standard way to share mutable state between threads. It is also where most people first meet a Send or Sync error. Each layer adds its own bounds on T, and the compiler combines them. After this chapter you should be able to work out those bounds yourself.
The two layers
Arc<T> is an atomically reference-counted pointer. Mutex<T> guards a value so that only one thread at a time can reach it. Each type implements Send and Sync conditionally, based on what T is.
| Type | Is `Send` when | Is `Sync` when |
|---|---|---|
| `Arc<T>` | `T: Send + Sync` | `T: Send + Sync` |
| `Mutex<T>` | `T: Send` | `T: Send` |
| `RwLock<T>` | `T: Send` | `T: Send + Sync` |
| `Rc<T>` | never | never |
| `MutexGuard<'_, T>` | never | `T: Sync` |
Put the first two rows together. Arc<Mutex<T>> is Send only if Mutex<T> is both Send and Sync. Mutex<T> is both whenever T: Send. So the whole bound collapses to one condition: Arc<Mutex<T>> is Send and Sync exactly when T: Send.
Why each bound exists
Arc needs T: Sync. Cloning an Arc and sending the clone to another thread gives that thread a shared &T. Sharing &T across threads is what Sync means.
Arc needs T: Send. The last Arc to be dropped frees T, and that may happen on any thread. Dropping a value on a different thread from where it was created is effectively a move to that thread. If T is not Send, that move is unsound.
Mutex asks only for T: Send. The mutex lets just one thread touch the value at a time, and each thread that locks it gets exclusive access. A thread that locks the mutex can therefore use T as if it had been moved there, so Send is enough. Mutex<T> does not require T: Sync. A Mutex can make a type that is not Sync usable from many threads.
The basic case
This is the example from the topic plan. i32 is Send, so Arc<Mutex<i32>> is Send and each thread can own a clone.
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 || {
*counter.lock().unwrap() += 1;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
}It prints 4. The shadowed counter inside the loop is a fresh Arc clone. The move closure takes that clone, so the closure is Send and 'static, which thread::spawn requires.
A mutex rescues a type that is not Sync
Cell<i32> is Send but not Sync. On its own, Arc<Cell<i32>> is not Send, because Arc<T> needs T: Sync. Inside a Mutex the problem goes away. You can check the bounds with the empty-function trick:
use std::cell::Cell;
use std::sync::{Arc, Mutex};
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<Mutex<Cell<i32>>>();
assert_sync::<Mutex<Cell<i32>>>();
assert_send::<Arc<Mutex<Cell<i32>>>>();
assert_sync::<Arc<Mutex<Cell<i32>>>>();
// Would fail to compile if uncommented: Cell<i32> is not Sync.
// assert_send::<Arc<Cell<i32>>>();
}The mutex supplies the missing guarantee. No two threads can reach the Cell at once, so its unsynchronized interior mutability cannot race.
What fails, and why
Arc<RefCell<T>>
A common first attempt is to reach for RefCell, the single-threaded cousin of Mutex.
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(RefCell::new(0));
let d = Arc::clone(&data);
let handle = thread::spawn(move || {
*d.borrow_mut() += 1;
});
handle.join().unwrap();
}This does not compile. The compiler reports that RefCell<i32> cannot be shared between threads safely, because Sync is not implemented for it. It adds that this is required for Arc<RefCell<i32>> to implement Send. Read the message from the bottom up. The closure captures an Arc<RefCell<i32>>. Arc<T>: Send needs T: Sync. RefCell<i32> is not Sync. The fix is to replace RefCell with Mutex.
Mutex<Rc<T>>
Wrapping an Rc in a mutex does not help. Mutex<T> needs T: Send, and Rc<T> is never Send. The mutex protects against simultaneous access, but Rc's non-atomic reference count is also shared with every other clone of that Rc. Those clones are not behind the lock. Use Arc instead of Rc for the inner pointer.
Trait objects need an explicit Send
A trait object forgets everything about the concrete type except what you write in its type. Box<dyn FnOnce() -> i32> is not Send, so a Mutex around a Vec of them is not Send either. Add the bound to the type:
use std::sync::{Arc, Mutex};
use std::thread;
type Job = Box<dyn FnOnce() -> i32 + Send>;
fn main() {
let queue: Arc<Mutex<Vec<Job>>> = Arc::new(Mutex::new(Vec::new()));
{
let mut q = queue.lock().unwrap();
for i in 1..=3 {
q.push(Box::new(move || i * 10));
}
}
let worker = {
let queue = Arc::clone(&queue);
thread::spawn(move || {
let mut total = 0;
loop {
let job = queue.lock().unwrap().pop();
match job {
Some(j) => total += j(),
None => break,
}
}
total
})
};
println!("{}", worker.join().unwrap());
}This prints 60. Remove + Send from the Job alias and the program stops compiling, with an error that dyn FnOnce() -> i32 cannot be sent between threads safely.
Note how the guard is handled in the worker. The temporary MutexGuard from queue.lock().unwrap() is dropped at the end of the let job = ...; statement. The job then runs without the lock held, so other workers are not blocked while it runs.
The guard is not Send
MutexGuard is deliberately not Send. On some platforms a lock must be released by the thread that took it. As a result, you cannot hold a guard across a thread::spawn boundary, and you cannot hold one across an .await in a future that must be Send. If you see an error naming MutexGuard, shorten the guard's scope with a block or an explicit drop before the spawn or .await.
Choosing between Mutex and RwLock
RwLock<T> allows many readers at once, and that changes its bounds. Several threads can hold &T simultaneously, so RwLock<T>: Sync needs T: Send + Sync. With Mutex, only T: Send is needed. That makes Mutex<Cell<i32>> valid while RwLock<Cell<i32>> is not shareable. If T is not Sync, Mutex is your only lock option.
Debugging checklist
When Arc<Mutex<T>> fails to compile, work through these steps:
- Find the innermost type named in the error. It is usually the
Tor a field ofT. - Check whether that type is
Send.Rc, raw pointers, andMutexGuardare common causes. - If a
dyn Traitis involved, add+ Send(and+ Synconly if you share it behindArcwithout a mutex). - Confirm you cloned the
Arcbeforemove, so each closure owns its own handle. - Replace
RefCellwithMutexandRcwithArc.
Exercise
A teammate writes Arc<Mutex<Vec<Rc<String>>>> and sends a clone to a spawned thread. The compiler rejects it. Which bound fails, and what is the smallest change that fixes it?
Show answer
Arc<Mutex<X>> is Send only if X: Send. Here X is Vec<Rc<String>>, which is Send only if Rc<String> is Send. Rc is never Send because its reference count is not atomic. The smallest fix is to replace Rc<String> with Arc<String>. The mutex does not help, because other clones of an Rc could live outside the lock.
Exercise
Why does Arc<Mutex<Cell<i32>>> compile as a Send value while Arc<Cell<i32>> does not?
Show answer
Arc<T> is Send only if T: Send + Sync. Cell<i32> is not Sync, so Arc<Cell<i32>> fails. Mutex<T> is both Send and Sync whenever T: Send, and Cell<i32> is Send. So Mutex<Cell<i32>> is Send + Sync, and the Arc bound is met.