Sub topic 10
Arc<Mutex<T>> and the bounds it needs
This chapter assumes you know thread::spawn, move closures, and trait bounds. It also assumes you have met Send and Sync as marker traits. Here you will see why the standard pattern for shared mutable state satisfies both.
The pattern
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());
}This prints 4. Each thread owns its own Arc clone, and all clones point to one Mutex<i32>. thread::spawn requires the closure to be Send, so the captured Arc<Mutex<i32>> must be Send.
The bounds, layer by layer
The standard library implements the traits conditionally. Each wrapper passes the question down to the type it contains.
| Type | Send when | Sync when |
|---|---|---|
| `Arc<T>` | `T: Send + Sync` | `T: Send + Sync` |
| `Mutex<T>` | `T: Send` | `T: Send` |
| `MutexGuard<T>` | never | `T: Sync` |
Arc<T> needs both traits because its clones can live on different threads. Any thread can drop the last clone, and the value is destroyed there, so T must be Send. All clones can also hand out &T at once, so T must be Sync.
Mutex<T> is Sync when T is only Send. The lock allows one thread at a time to reach the value, and that access can use &mut T. Handing the value to one thread at a time is the same as moving it between threads. So Mutex<Cell<i32>> is Sync, even though Cell<i32> is not.
Failing cases
The bounds explain two common errors.
Arc<Mutex<Rc<i32>>>is notSend.Rc<i32>is notSend, soMutex<Rc<i32>>is neitherSendnorSync.Arc<RefCell<i32>>is notSend.RefCell<i32>isSendbut notSync, andArcrequires both.
In the second case, the fix is to replace RefCell with Mutex, or with RwLock if reads dominate.
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(RefCell::new(0));
let handle = thread::spawn(move || {
*data.borrow_mut() += 1;
});
handle.join().unwrap();
}This does not compile. The error says RefCell<i32> cannot be shared between threads safely, and it points to the Sync requirement of Arc.
Why the guard is not Send
MutexGuard is not Send because some operating systems require the thread that locked a mutex to be the one that unlocks it. This matters in two situations.
- Moving a guard into
thread::spawnfails to compile. - In async code, holding a guard across an
.awaitmakes the future non-Send.
Exercise
Is Arc<Mutex<Cell<i32>>> Send? Explain using the bounds in the table.
Show answer
Yes. Cell<i32> is Send, so Mutex<Cell<i32>> is both Send and Sync, because Mutex<T> needs only T: Send for either trait. Arc then requires Send + Sync from the Mutex, and both hold.