Share state with a small critical section.
Separate cross-thread ownership from synchronized mutation.
01 Understand the contract
Arc<T> provides atomic reference-counted ownership across threads. It does not make arbitrary mutation safe by itself. A Mutex<T> protects access through a guard that unlocks when dropped. Keep the critical section short and avoid slow I/O while holding a synchronous lock. Lock poisoning signals that a thread panicked while holding the lock; decide whether to propagate, recover, or terminate based on the data invariant. In async code, never casually hold a std MutexGuard across await.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::{
sync::{Arc, Mutex},
thread,
};
fn main() {
let count = Arc::new(Mutex::new(0_u32));
let mut workers = Vec::new();
for _ in 0..4 {
let count = Arc::clone(&count);
workers.push(thread::spawn(move || {
for _ in 0..100 {
*count.lock().unwrap() += 1;
}
}));
}
for worker in workers {
worker.join().unwrap();
}
println!("{}", *count.lock().unwrap());
}400
- 1
Each Arc clone shares the same mutex-protected counter.
- 2
Every increment holds a short-lived guard.
- 3
Joining all workers makes the final result deterministic.
cargo run -p lesson_arc_mutex03 Mind the boundary
04 Your next build
Protect a vector with Arc<Mutex<_>>, push one value per worker, sort afterward, and assert all values arrived.
Reveal one possible solution +
use std::{
sync::{Arc, Mutex},
thread,
};
fn main() {
let values = Arc::new(Mutex::new(Vec::new()));
let jobs: Vec<_> = (0..3)
.map(|n| {
let v = Arc::clone(&values);
thread::spawn(move || v.lock().unwrap().push(n))
})
.collect();
for job in jobs {
job.join().unwrap();
}
let mut result = values.lock().unwrap().clone();
result.sort();
assert_eq!(result, [0, 1, 2]);
}05 Check your reasoning
What protects the mutable payload in Arc<Mutex<T>>?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.