Sub topic 7
Putting it together: Arc<Mutex<T>>
This chapter combines Arc and Mutex into the standard pattern for sharing mutable data between threads. It assumes you know Rust ownership, borrowing and lifetimes, closures and the move keyword, std::thread::spawn with JoinHandle, and basic Result and unwrap handling.
Why you need both types
Each type solves one half of the problem.
Arc<T>is an atomically reference-counted pointer. It lets several threads own the same value. When the lastArcis dropped, the value is freed. AnArcgives out only shared (&T) access.Mutex<T>is a mutual exclusion lock that owns its data. It lets one thread at a time obtain&mut Taccess through a guard.
If you use only Arc<i32>, the threads share the value but cannot change it. If you use only Mutex<i32>, it can be changed safely, but a spawned thread needs to own it, and only one thread can. The combination Arc<Mutex<T>> gives you shared ownership plus serialized mutation.
| Type | Shared ownership across threads | Mutation | Notes |
|---|---|---|---|
| `Rc<RefCell<T>>` | No (not `Send`) | Yes, checked at run time | Single-threaded only |
| `Arc<T>` | Yes | No | Read-only sharing |
| `Mutex<T>` | No | Yes, one thread at a time | Needs an owner or a borrow |
| `Arc<Mutex<T>>` | Yes | Yes, one thread at a time | The standard pattern |
A complete 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. Walk through it in four steps.
Arc::new(Mutex::new(0))puts the integer inside the mutex and the mutex inside theArc. The order matters: theArcis the outer layer, so cloning it copies only a pointer.let counter = Arc::clone(&counter);runs once per loop iteration and shadows the outer name. Each thread gets its own handle to the same allocation. The strong count goes up by one for each clone.movetransfers that clone into the closure. The thread now owns anArc, so the closure is'static, whichthread::spawnrequires.counter.lock().unwrap()blocks until the lock is free and returns aMutexGuard.*guard += 1goes throughDerefMutto change the integer. The guard is dropped at the end of each loop iteration, which releases the lock.
Prefer Arc::clone(&counter) over counter.clone(). Both work, but the first makes it clear that you are copying a pointer and not the data.
What the types look like
Reading the types helps when compiler errors appear. In the example, counter has the type Arc<Mutex<i32>>.
counter.lock()auto-dereferences through theArcto reachMutex::lock. This works becauseArc<T>implementsDeref<Target = T>.lock()returnsLockResult<MutexGuard<'_, i32>>, which is aResultthat can hold a poison error. That is whyunwrap()appears. Poisoning is covered in a later chapter.- The guard borrows from the
Mutex, so it cannot outlive theArcit came from.
How the compiler checks this
Arc<Mutex<T>> compiles across threads because of the marker traits Send and Sync.
Arc<T>isSendandSynconly ifTis bothSendandSync.Mutex<T>isSyncifTisSend. This is the useful rule: a mutex lets you share a type that is not itselfSync, because only one thread touches the data at a time.
You can see the first rule fail if you swap Arc for Rc.
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let data = Rc::new(Mutex::new(0));
let data2 = Rc::clone(&data);
// Does not compile: `Rc<Mutex<i32>>` cannot be sent between threads safely.
let handle = thread::spawn(move || {
*data2.lock().unwrap() += 1;
});
handle.join().unwrap();
}Rc updates its reference count with plain, non-atomic operations. Two threads doing that at once could corrupt the count, so Rc does not implement Send, and the compiler rejects the program. Replacing Rc with Arc fixes it.
Where the lock is held
The guard holds the lock for exactly as long as it is alive. A named guard lives until the end of its scope. A temporary guard lives until the end of the statement.
use std::sync::{Arc, Mutex};
fn main() {
let shared = Arc::new(Mutex::new(vec![1, 2, 3]));
// Temporary guard: the lock is released at the semicolon.
shared.lock().unwrap().push(4);
// Named guard: the lock is held until `guard` goes out of scope.
{
let mut guard = shared.lock().unwrap();
guard.push(5);
}
println!("{:?}", shared.lock().unwrap());
}This prints [1, 2, 3, 4, 5]. Short temporaries are the easiest way to keep a critical section small. The next chapter covers that topic in detail.
Common errors
Locking the same mutex twice in one thread
Mutex is not reentrant. If a thread already holds the guard and calls lock() again on the same mutex, the call may deadlock or panic. The standard library does not specify which. Keep one guard per mutex per thread, and pass &mut T to helper functions instead of passing the Arc.
Forgetting to clone before `move`
If you write thread::spawn(move || { counter.lock()... }) without cloning, the first iteration moves the original Arc into the closure. The second iteration then fails with a "value moved in previous iteration of loop" error. Clone inside the loop, before the closure.
Cloning the data instead of the pointer
Writing Arc::new(Mutex::new(data.clone())) per thread creates separate counters. The program compiles and runs, but each thread updates its own copy. Create the Arc once and clone only the Arc.
Holding a guard across slow work
A guard that stays alive during computation or I/O makes the other threads wait. The result is correct but serialized, so you lose the benefit of having threads. Compute first, then lock briefly.
Sending a guard to another thread
MutexGuard is not Send. Some platforms require that the thread that locked a mutex also unlock it. Return or move the data you need, not the guard.
Expecting `Arc` to give mutable access
Arc::get_mut and Arc::make_mut exist, but they work only when there is a single owner or when the data is Clone. They do not coordinate between threads. For shared mutation, put the data in a lock.
Getting the value back out
When all the threads have finished, you often want the data itself. If you hold the only remaining Arc, you can unwrap it and then consume the mutex.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let results = Arc::new(Mutex::new(Vec::new()));
let handles: Vec<_> = (0..4)
.map(|id| {
let results = Arc::clone(&results);
thread::spawn(move || {
results.lock().unwrap().push(id * 10);
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
let mut values = Arc::try_unwrap(results)
.expect("other Arc handles still exist")
.into_inner()
.unwrap();
values.sort();
println!("{:?}", values);
}The program prints [0, 10, 20, 30]. Arc::try_unwrap succeeds only when the strong count is 1. That holds here because each thread's clone was dropped when its closure finished and was joined. Mutex::into_inner consumes the mutex and returns a LockResult<T>. No lock is needed because nothing else can reach the data. Locking and cloning the vector, as in results.lock().unwrap().clone(), also works and is simpler when you do not need ownership.
Design guidance
- Put related fields that must change together in one mutex, for example
Mutex<State>whereStateis a struct. Splitting them across two mutexes lets another thread see a half-updated state, and it introduces lock-ordering risk. - Keep the type
Arc<Mutex<T>>out of public APIs when you can. Wrap it in a struct with methods such asincrement()orsnapshot(), so callers cannot hold the guard by accident. - Use the pattern when threads must read and write the same data. If the data is read-only after setup, a plain
Arc<T>is enough and needs no lock. - Choose a lighter tool for simple cases. An atomic integer replaces
Arc<Mutex<usize>>for a counter, and later chapters cover that along withRwLock, scoped threads and channels.
Exercise
A teammate writes this loop and gets a compile error about a moved value. What is wrong, and what is the fix? let counter = Arc::new(Mutex::new(0)); for _ in 0..4 { thread::spawn(move || { *counter.lock().unwrap() += 1; }); }
Show answer
The move closure takes ownership of counter in the first iteration, so the second iteration has no value left to move. Create a clone inside the loop before the closure, with let counter = Arc::clone(&counter);. Each thread then owns its own Arc handle to the same mutex. Also keep the JoinHandle values and call join() so the main thread does not exit before the workers finish.
Exercise
Why does Arc<Mutex<Vec<i32>>> satisfy the compiler's Send requirement for thread::spawn, while Rc<Mutex<Vec<i32>>> does not?
Show answer
Arc uses atomic operations to update its reference count, so it is Send when its contents are Send and Sync. Mutex<Vec<i32>> is Sync because Vec<i32> is Send. Rc uses non-atomic counting, so it is not Send, and the compiler rejects moving it into another thread.