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 and join. It also assumes you know why Send and Sync exist. Channels move values between threads. Sometimes several threads need to read and update the same value instead, such as a counter, a cache, or a list of results. Rust supports this with shared state, and the type system forces you to do it safely.
Why one owner is not enough
A spawned thread may outlive the function that created it, so a closure passed to thread::spawn cannot borrow local variables. If you move a value into one thread, no other thread can have it. To give several threads access to the same value you need two things:
- Shared ownership, so the value lives until the last thread is done with it.
Arc<T>provides this. - Controlled mutation, so only one thread changes the value at a time.
Mutex<T>provides this.
Together they form Arc<Mutex<T>>, the standard type for mutable state shared across threads.
Arc: shared ownership across threads
Arc<T> is an atomically reference-counted pointer. Calling Arc::clone(&a) does not copy T. It creates another pointer to the same allocation and increments a counter. When the last Arc is dropped, the counter reaches zero and T is dropped.
Rc<T> does the same job with a plain counter. That counter is not safe to update from two threads at once, so Rc<T> does not implement Send. If you try to move an Rc into thread::spawn, the compiler reports that Rc<_> cannot be sent between threads safely. The fix is to use Arc, which pays a small cost for atomic increments and decrements.
Arc<T> is only Send when T is both Send and Sync. An Arc gives out shared (&T) access from several threads, so T must be safe to reference from several threads at once.
An Arc alone gives you only immutable access. You cannot write *arc += 1, because several owners exist. You need interior mutability that is safe across threads.
Mutex: one thread at a time
A Mutex<T> (mutual exclusion lock) wraps a value and allows only one thread to access it at a time. Unlike mutexes in C or C++, the data lives inside the mutex. You cannot reach the T without locking, so you cannot forget to lock.
lock() blocks until the mutex is free and returns LockResult<MutexGuard<T>>. The guard dereferences to T and unlocks the mutex when it is dropped.
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());
}Each iteration clones the Arc and moves the clone into the thread. In the loop body, counter.lock().unwrap() produces a guard, * reaches the integer, and += 1 updates it. The guard is a temporary, so it is dropped at the end of that statement and the lock is released. The output is always count = 4000. Without the mutex, this would be a data race, and Rust would refuse to compile the unsynchronized version.
Keep the guard short
The lock stays held for as long as the guard exists. A common mistake is keeping a guard alive across slow work, which makes the other threads wait and removes the benefit of having threads at all.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let mut handles = Vec::new();
for id in 0..3 {
let log = Arc::clone(&log);
handles.push(thread::spawn(move || {
// Do the slow work first, without holding the lock.
thread::sleep(Duration::from_millis(10 * id));
let line = format!("worker {id} finished");
// Lock only for the push. The guard is dropped at the end of the block.
{
let mut guard = log.lock().unwrap();
guard.push(line);
}
// More slow work happens after the lock is released.
thread::sleep(Duration::from_millis(10));
}));
}
for h in handles {
h.join().unwrap();
}
let mut lines = log.lock().unwrap().clone();
lines.sort();
println!("{lines:?}");
}Three habits keep lock time short:
- Compute values before locking, then lock only to read or write.
- Use an inner block, or call
drop(guard), to release the lock before the end of the function. - Do not call
send,join, file or network I/O, or other locks while holding a guard unless you have a reason.
Deadlocks are still possible
Rust prevents data races. It does not prevent deadlocks. A deadlock happens when threads wait on each other forever. Two common causes:
- Thread A locks
m1thenm2, while thread B locksm2thenm1. Each holds one lock and waits for the other. The fix is to always acquire multiple locks in the same order. - A thread locks a mutex it already holds.
Mutexis not reentrant. The secondlock()may deadlock or panic, and the standard library does not promise which.
The second case often hides in a temporary guard. In match m.lock().unwrap().get(&k) { ... }, the guard lives for the entire match, including every arm. If an arm calls m.lock() again, the thread deadlocks. Bind the result to a variable first so the guard drops at the end of that statement.
Poisoning
If a thread panics while holding a guard, the data may be half updated. To flag this, the mutex becomes poisoned. Every later lock() returns Err(PoisonError) instead of Ok. This is why lock() returns a Result and why you see .unwrap() everywhere. With unwrap, one panic spreads to every thread that touches the mutex.
You can choose to recover. PoisonError::into_inner returns the guard anyway:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let d = Arc::clone(&data);
let result = thread::spawn(move || {
let mut guard = d.lock().unwrap();
guard.push(4);
panic!("failed while holding the lock");
})
.join();
println!("thread panicked: {}", result.is_err());
println!("poisoned: {}", data.is_poisoned());
let guard = match data.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
println!("{:?}", *guard);
}The program prints the panic message to standard error, then thread panicked: true, poisoned: true, and [1, 2, 3, 4]. Recovering is safe only if you can check or repair the data. For a counter, recovering is usually fine. For a structure with invariants spanning several fields, treating the poison as a fatal error is often the better choice.
try_lock and getting the value back out
lock() blocks. try_lock() returns immediately with Err(TryLockError::WouldBlock) if another thread holds the lock. It also reports poisoning. This is useful when a thread has other work it can do instead of waiting, such as skipping a periodic update.
After all threads finish, you often want the plain value back. If you hold the only remaining Arc, you can unwrap it:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*counter.lock().unwrap() += 250;
}));
}
for h in handles {
h.join().unwrap();
}
let total = Arc::try_unwrap(counter)
.expect("other Arc clones still exist")
.into_inner()
.unwrap();
println!("total = {total}");
}Arc::try_unwrap succeeds only when the strong count is 1. Mutex::into_inner consumes the mutex and returns the LockResult<T>, so a poisoned mutex still reports an error there.
Reading often, writing rarely: RwLock
RwLock<T> allows many readers at once or one writer. It fits data that is read far more often than written, such as configuration. Call read() for shared access and write() for exclusive access. It poisons the same way, and it has a cost: for short critical sections a plain Mutex is often as fast or faster. Start with Mutex and change to RwLock only if measurement shows readers waiting on each other.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Rc<...>` cannot be sent between threads safely | `Rc` is not `Send` | Use `Arc` |
| Use of moved value inside a loop | The original `Arc` was moved into the first closure | Clone it inside the loop, as in the examples |
| `cannot assign` through an `Arc` | `Arc` gives only shared access | Wrap the value in `Mutex` or `RwLock` |
| Program hangs | Deadlock from lock ordering or a re-locked mutex | Fix the lock order, shorten guard lifetimes |
| Every thread panics with `PoisonError` | One thread panicked while holding the lock and the others call `unwrap` | Handle `Err` and use `into_inner`, or fix the first panic |
| Threads run one after another | Guard held during slow work | Narrow the lock scope |
How this connects to channels
Both approaches are safe, but they model the problem differently. With channels, one thread owns a value at a time and ownership moves. With Arc<Mutex<T>>, all threads own the value together and take turns. The worker pool in a later chapter uses both: a Receiver shared through Arc<Mutex<_>> and results returned over a second channel.
Exercise
Four threads each run *counter.lock().unwrap() += 1; 1000 times on an Arc<Mutex<i32>>. A colleague changes the type to Arc<i32> and the statement to *counter += 1; to avoid locking overhead. What happens, and why?
Show answer
The program no longer compiles. Arc<i32> gives only shared (&) access, so assigning through it is rejected. This is the compiler preventing a data race. To mutate the value from several threads you need Mutex<i32> (or an atomic type such as AtomicI32) inside the Arc.
Exercise
A worker thread locks a Mutex<Vec<u32>>, pushes a value, and panics on the next line while still holding the guard. What does lock() return in the other threads afterward, and how can one of them still read the vector?
Show answer
lock() returns Err(PoisonError), because the mutex is poisoned. A thread can call poisoned.into_inner() on the error to get the guard and read the vector, or call data.lock().unwrap_or_else(|e| e.into_inner()). Doing so is appropriate only if the data is still meaningful after the panic.