Sub topic 7
Putting it together: Arc<Mutex<T>>
This chapter assumes you know ownership and borrowing, move closures, thread::spawn with JoinHandle, and Result with unwrap. Earlier chapters covered Arc for shared ownership and Mutex for mutual exclusion. Here you combine them.
Why the two types appear together
Each type solves half of the problem.
Arc<T>lets several threads own the same value. It gives you shared ownership, but only shared (read-only) access to the contents.Mutex<T>lets one thread at a time get mutable access to the value inside it. It does not provide shared ownership, so you cannot hand aMutexto several threads by itself.
Wrapping a Mutex in an Arc gives you both: many owners, and exclusive access to the data whenever one owner mutates it.
A working example
Eight threads each add 1000 to one shared counter.
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!("{}", *counter.lock().unwrap());
}The program always prints 8000.
How the pieces work
Arc::new(Mutex::new(0))creates the counter and a reference count of 1.- Inside the loop,
Arc::clone(&counter)creates a new handle to the same allocation. It does not copy the number. It increments the atomic reference count. - The
let counter = ...line shadows the outer name, so themoveclosure takes ownership of that thread's own clone. counter.lock()blocks until the lock is free, then returns aResultholding aMutexGuard. Theunwraphandles the poisoning case, which a later chapter covers.*guard += 1mutates the data through the guard. The guard dereferences to the inner value.- At the end of each loop iteration the guard goes out of scope. Its
Dropimplementation releases the lock. - After
joinreturns for every thread, only the original handle remains, and the finallock()reads the total.
The following diagram shows the ownership and the lock.
Common errors
The compiler catches most mistakes with this pattern.
| Mistake | What happens |
|---|---|
| Moving `counter` into the closure without cloning | Compile error: use of moved value on the second loop iteration |
| Using `Rc` instead of `Arc` | Compile error: `Rc` cannot be sent between threads safely |
| Forgetting `mut` on the guard | Compile error: cannot assign through the guard |
| Cloning the inner data instead of the `Arc` | Each thread updates its own copy, so the shared total is wrong |
The last mistake does not produce a compiler error, so check what you clone. Arc::clone(&counter) is the cheap, correct call. Calling .lock().unwrap().clone() copies the data out of the lock and shares nothing.
Exercise
Exercise
In the counter example, what would the program print if each thread created its own Mutex::new(0) instead of cloning the shared Arc, and why would the compiler still accept it?
Show answer
Each thread would increment a separate counter, so the shared counter in main would stay at 0 and the program would print 0. The compiler accepts it because every thread uses a valid, thread-safe value. Nothing in the types says the threads must share one Mutex. Sharing happens only when you clone the same Arc.