Sub topic 12
Shared state with Arc and Mutex
This chapter assumes you know ownership and borrowing, closures with move, Result and unwrap, and the basics of thread::spawn. It also assumes you have seen Send and Sync and know that channels pass values between threads. Channels move data from one thread to another. Sometimes several threads need to read and change the same value. For that, Rust uses Arc and Mutex.
The problem: one value, many threads
A move closure gives a spawned thread ownership of the values it captures. If you move a value into one thread, you cannot use it anywhere else. Borrowing does not help either. A plain reference cannot outlive the function that created it, and thread::spawn requires a 'static closure.
Two tools solve this:
Arc<T>is an atomically reference-counted pointer. Cloning it makes another owner of the same value. The value is freed when the lastArcis dropped.Mutex<T>is a mutual exclusion lock that wraps a value. Only one thread can hold the lock at a time, and the wrapped value is reachable only through the lock.
Rc<T> is the single-threaded version of Arc<T>. It is not Send, so the compiler rejects it in a spawned closure. Arc uses atomic operations for its count, which costs slightly more, and that is why it is safe to share.
A 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..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
*counter.lock().unwrap() += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("count = {}", *counter.lock().unwrap());
}The program always prints count = 4000. Here is how it works:
Arc::new(Mutex::new(0))puts the integer inside a lock, and puts the lock inside a shared pointer.- Each loop iteration clones the
Arcand moves the clone into its thread. The clone copies the pointer and bumps the count. It does not copy the integer. counter.lock()blocks until the lock is free, then returns aMutexGuard.*guard += 1changes the value through the guard.- The guard is a temporary in that statement, so it drops at the semicolon and releases the lock.
Why the lock is part of the type
In many languages the lock sits next to the data, and you must remember to take it. In Rust, Mutex<T> owns the T. The only way to reach the data is lock(), so you cannot forget the lock. This is how Rust turns a possible data race into a compile-time error.
The guard also releases the lock automatically when it goes out of scope. You never call an unlock function.
Common errors
Holding the guard too long
The lock stays held for as long as the guard is alive. If you bind the guard to a variable and then do slow work, every other thread waits.
use std::sync::Mutex;
fn main() {
let data = Mutex::new(vec![1, 2, 3]);
let len = {
let guard = data.lock().unwrap();
guard.len()
};
println!("len = {len}");
}The inner block ends right after reading the length, so the lock is released before anything else runs. Keep the critical section small. Do not send on a channel or sleep while holding a guard unless you must.
Deadlock
A deadlock happens when threads wait on each other forever. Locking the same Mutex twice in one thread will hang or panic. Two threads taking two locks in opposite order can also deadlock. Rust does not catch this at compile time. The usual fix is to always take locks in the same order.
Poisoning
If a thread panics while holding the guard, the mutex becomes poisoned. Later calls to lock() return Err. The unwrap() in the examples turns that into a panic in the next thread. If the data is still usable, you can recover it with lock().unwrap_or_else(|e| e.into_inner()).
Forgetting `Arc`
Moving a Mutex into the first thread, then using it in the second, fails with a "use of moved value" error. Clone an Arc for each thread instead.
Exercises
Exercise
Why does the counter example call Arc::clone(&counter) inside the loop instead of passing counter straight into thread::spawn?
Show answer
A move closure takes ownership of what it captures. Passing counter itself would move it into the first thread, and the next iteration would fail with a use-of-moved-value error. Cloning the Arc gives each thread its own owner of the same Mutex.
Exercise
A thread panics while holding a MutexGuard. What does the next call to lock() return, and how can you still reach the data?
Show answer
It returns Err(PoisonError) because the mutex is poisoned. Call into_inner() on the error to get the guard back, for example lock().unwrap_or_else(|e| e.into_inner()).