
Understand it
Arc<T> is Rc with an atomic count so it can cross threads. Mutex<T> holds the data itself rather than guarding it by convention, so the only way to reach the value is to lock — and the guard unlocks when it drops, which means a forgotten unlock is not a bug you can write.
Arc<T> is an atomically reference-counted owner that can be cloned across threads when the contained type permits it. Mutex<T> protects mutable data with a lock. Together, Arc<Mutex<T>> lets workers own handles to one allocation while only one guard at a time accesses the protected value. Cloning an Arc clones a handle, not the inner data. The guard from lock() releases the lock when it leaves scope. RwLock<T> is a close relative: it allows many readers or one writer at a time, which can help when reads far outnumber writes.
In a counter example, each worker clones the Arc, locks the mutex, increments the count, and drops the guard. If a worker holds the guard while doing slow I/O, every other worker waits unnecessarily. Keep the critical section small and do unrelated work before or after it. Treat lock() as fallible because a panic while holding the lock can poison a standard mutex; decide how the application handles that state.
Try writing the counter first without synchronization and read the compiler error rather than fighting it. Add Arc<Mutex<_>>, start several workers, join them, and compare the final count with the predicted sum. Then move a long sleep inside the lock and measure the slowdown. The type system prevents an unsynchronized data race, but the lock still has performance and deadlock costs. Use a channel when workers can hand off owned messages instead of editing shared state; use a mutex when a shared invariant must be updated atomically.
Beware of hidden lock retention: a guard stored in a local variable stays live until it is dropped or leaves scope. Explicitly shorten its scope before calling another function that may need the same lock. This is both a responsiveness issue and a common path to self-deadlock.
Read the code
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..8 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*counter.lock().unwrap() += 1;
}));
}
for handle in handles { handle.join().unwrap(); }
println!("{}", *counter.lock().unwrap());The data lives inside the lock, so unlocked access is unrepresentable.
Practice starter
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
let counter = Rc::new(Mutex::new(0));
thread::spawn(move || {
*counter.lock().unwrap() += 1;
});Try it
Increment one counter from several threads.
What success looks like: The final total equals the number of increments, every run.
Check your understanding
Why can that Rc not cross the thread boundary?
Reveal the answer
- A Mutex cannot hold a plain integer counter
- Rc is not Send, so it cannot move to another thread
- lock() is unsafe and needs an unsafe block
Rc uses a non-atomic count; Arc is the thread-safe version.
Go deeper
Common misconception: “Wrapping a value in a Mutex makes it shareable across threads, whichever pointer holds it.”
The Mutex protects the value, but the handle has to cross too. Rc's count is not atomic, so Rc<Mutex<i32>> is not Send; use Arc<Mutex<i32>>.
- Share the handle:
Arc::new(Mutex::new(0))creates one allocation. Each pass of the loop clones theArc, a new handle to the same mutex, and moves it into a worker. - Hold the guard:
counter.lock().unwrap()returns a guard, and*reaches the integer through it. The guard is a temporary, so it unlocks at the end of that statement. - Read the total: After all eight handles are joined, no worker can still hold the lock, so the final print shows 8 on every run.
Transfer challenge: Replace the Mutex with an RwLock: update with write() in the workers and read the total with read(). Predict whether the output changes, then say which lock suits this counter.
Connections
- Channels: Message passing with mpsc
- Send & Sync: The traits behind thread safety
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Shared State (courseId "concurrency", lessonId "shared-state") Link: https://crabrix.com/learn/concurrency/shared-state/ Goal: The lock guard unlocks on drop, so there is no unlock to forget. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/shared-state) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.