Shared state across threads.
Explain Arc, Mutex, Send, and Sync without treating a lock as magic.
The idea behind the syntax.
Some concurrent programs need several threads to access one shared state. Arc<T> is an atomically reference-counted owner that can be cloned across threads. Mutex<T> protects a value so one thread at a time can hold its guard and mutate it. Arc<Mutex<T>> combines shared ownership with exclusive access, but it does not decide which operation is logically correct or how long a lock should be held.
Send and Sync are marker traits that describe cross-thread safety properties. Send permits ownership of a value to move to another thread. Sync means shared references to a type can be used from multiple threads safely. These traits are usually derived automatically from component types; they do not mean every sequence of operations on a type is race-free at the business-logic level.
What Rust is checking.
A mutex guard unlocks when it is dropped. Keep its scope small so unrelated work is not blocked. Holding a lock while waiting on I/O or another lock can create long pauses or deadlock. Poisoning reports that a thread panicked while holding a lock; the next user must decide whether the protected state can still be trusted.
An atomic operation or a channel may fit better than a mutex for simple counters or one-way ownership transfer. The choice depends on the invariant: which changes must appear together, and who needs to observe them? The examples show the mechanism, but the important theoretical step is identifying the smallest state that must be shared and the point at which each operation is complete.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Arc, Mutex & lock scope
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.
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
- Each Arc clone shares the same mutex-protected counter.
- Every increment holds a short-lived guard.
- Joining all workers makes the final result deterministic.
The boundary: Arc only synchronizes its reference count. The payload still needs an appropriate synchronization strategy for mutation.
Send, Sync & atomics
Send means ownership of a value can be transferred between threads. Sync means shared references to a value can be sent between threads. These auto traits are derived from a type’s fields unless constrained otherwise. Rc is neither Send nor Sync because its reference count is non-atomic. Atomics support synchronized operations on individual primitive values; choosing a memory ordering is a correctness decision. Relaxed is suitable for an independent counter whose value does not publish other data, especially when joins provide the final completion synchronization.
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use std::thread;
fn main() {
let count = Arc::new(AtomicUsize::new(0));
let workers: Vec<_> = (0..3)
.map(|_| {
let c = Arc::clone(&count);
thread::spawn(move || {
c.fetch_add(1, Ordering::Relaxed);
})
})
.collect();
for worker in workers {
worker.join().unwrap();
}
println!("{}", count.load(Ordering::Relaxed));
}3
- Atomic fetch_add avoids a lost increment.
- This counter does not publish any separate payload.
- join ensures each worker has finished before the final load.
The boundary: Relaxed does not establish ordering for unrelated data. Use a proven synchronization design rather than guessing a memory ordering.
Keep this model.
Arc shares ownership, Mutex coordinates exclusive access, and Send/Sync describe type-level thread safety. None replaces a clear invariant for shared state.