Rust Concurrency: Spawning Threads, mpsc Channels, and Arc<Mutex<T>>
Ownership rules make data races a compile error. Sharing with Arc<Mutex>, sending with mpsc, and the lock ordering and sender-lifetime mistakes that hang.

Quick Summary
std::thread::spawn starts an operating-system thread and returns a JoinHandle<T>. The closure must be Send + 'static, which means it cannot borrow local variables — it has to own or share them. Sharing mutable state across threads needs Arc<Mutex<T>> (or Arc<RwLock<T>>), because Rc is not Send and the compiler refuses to build the version that would race.
Channels are the other model. std::sync::mpsc::channel gives a multi-producer, single-consumer queue: any number of senders, one receiver, and dropping all senders ends the receiver's iteration cleanly. Bounded channels (sync_channel(n)) apply backpressure; unbounded ones grow memory without limit when the consumer falls behind.
Two rules decide most designs. Prefer message passing when threads own their data and you want no shared invariants; prefer shared state when many threads read one structure and updates are small. And never hold a lock while performing I/O or blocking work — a MutexGuard held across a send, a sleep, or a network call is the standard deadlock.
Basic syntax and query signatures
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
fn main() {
// Spawn with ownership, join to get the result
let handle = thread::spawn(|| 21 * 2);
let value = handle.join().unwrap();
assert_eq!(value, 42);
// Shared mutable state
let counter = Arc::new(Mutex::new(0u64));
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(); }
assert_eq!(*counter.lock().unwrap(), 4000);
// Channels
let (tx, rx) = mpsc::channel::<String>();
for i in 0..3 {
let tx = tx.clone(); // multiple producers
thread::spawn(move || {
tx.send(format!("job {i}")).unwrap();
}); // tx dropped here: producer ends
}
drop(tx); // drop the original, or recv() blocks forever
for msg in rx { // ends when all senders are gone
println!("{msg}");
}
}Scoped threads (Rust 1.63+) can borrow from the enclosing scope, which removes the Arc in read-only cases:
let data = vec![1, 2, 3, 4];
thread::scope(|s| {
let (a, b) = data.split_at(2);
s.spawn(|| println!("{:?}", a.iter().sum::<i32>()));
s.spawn(|| println!("{:?}", b.iter().sum::<i32>()));
}); // all scoped threads joined here
println!("{data:?}"); // still owned by the parentBounded channels and timeouts:
let (tx, rx) = mpsc::sync_channel::<u8>(2); // capacity 2: send blocks when full
match rx.recv_timeout(std::time::Duration::from_millis(100)) {
Ok(v) => println!("{v}"),
Err(mpsc::RecvTimeoutError::Timeout) => println!("nothing yet"),
Err(mpsc::RecvTimeoutError::Disconnected) => println!("all senders gone"),
}Key comparison table
| Primitive | Sharing model | Thread safe | Blocking | Typical use |
|---|---|---|---|---|
thread::spawn | Owned closure | Send + 'static required | n/a | CPU work, isolation |
thread::scope | Borrowed closure | Bounded by scope | Joins on exit | Parallel reads of one buffer |
Arc<Mutex<T>> | Shared mutable | Yes | lock() blocks | Counters, caches, single-writer state |
Arc<RwLock<T>> | Shared, many readers | Yes | read()/write() | Read-heavy shared config |
AtomicU64 etc. | Shared, lock-free | Yes | Never | Counters, flags |
mpsc::channel | Message passing | Yes | recv() blocks | Task queues, fan-in |
mpsc::sync_channel(n) | Bounded | Yes | send() blocks when full | Backpressure |
| Channel call | On empty | On closed |
|---|---|---|
recv() | Blocks | Err(RecvError) |
try_recv() | Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) |
recv_timeout(d) | Waits up to d, then Timeout | Disconnected |
iter() / for | Blocks per item | Ends the loop |
send() | Succeeds (unbounded) or blocks (bounded) | Err(SendError(v)) |
Practical edge cases and deep dives
1. Forgetting to drop the original sender hangs the consumer
let (tx, rx) = mpsc::channel();
let tx2 = tx.clone();
thread::spawn(move || tx2.send(1).unwrap());
for v in rx { println!("{v}"); } // never ends: the original `tx` is still aliverx ends only when every sender is dropped. The fix is an explicit drop(tx) after cloning for the workers, or moving the original sender into the loop's last iteration. This hang has no error message and no timeout by default, so it reads as a deadlock in production.
2. Sending while holding a lock is a deadlock waiting to happen
let state = Arc::new(Mutex::new(Vec::new()));
let (tx, rx) = mpsc::channel();
// Bad: the guard is held across the send
let s = Arc::clone(&state);
let tx1 = tx.clone();
thread::spawn(move || {
let mut guard = s.lock().unwrap();
tx1.send(guard.len()).unwrap(); // if the receiver wants the same lock, deadlock
guard.push(1);
});Release the lock before transferring control:
thread::spawn(move || {
let len = { let guard = s.lock().unwrap(); guard.len() }; // lock released here
tx1.send(len).unwrap();
});3. Two mutexes, opposite order
// Thread A: lock(a) then lock(b) Thread B: lock(b) then lock(a) -> deadlock
fn transfer(a: &Mutex<u64>, b: &Mutex<u64>, amount: u64) {
let mut ga = a.lock().unwrap();
let mut gb = b.lock().unwrap();
*ga -= amount; *gb += amount;
}std::sync::Mutex has no deadlock detection. Order the locks by address or by a stable id, or collapse both balances into one mutex-protected struct so there is only one lock to take.
4. A panicking thread poisons the mutex
let m = Arc::new(Mutex::new(0));
let m2 = Arc::clone(&m);
let h = thread::spawn(move || {
let _g = m2.lock().unwrap();
panic!("boom");
});
assert!(h.join().is_err()); // the panic is reported here
// Every later lock() returns Err: the data may be inconsistent
let recovered = m.lock().unwrap_or_else(|e| e.into_inner());into_inner() on the poison error gives access to the data while acknowledging that it may not satisfy its invariants. Treat poisoning as a signal to validate the value, not as an annoyance to unwrap away.
5. Threads that read shared data do not need Arc
let config = load_config();
let results: Vec<_> = config.shards.iter()
.map(|shard| {
thread::scope(|s| s.spawn(move || process(shard)))
})
.collect();thread::scope borrows, so config stays owned by the parent and no reference counting happens. Reach for Arc when the threads outlive the function or when they need shared mutable state.
6. Blocking work inside a thread pool needs a bound
let jobs = Arc::new(Mutex::new(Vec::<Job>::new()));
let mut handles = Vec::new();
for _ in 0..num_cpus::get() {
let jobs = Arc::clone(&jobs);
handles.push(thread::spawn(move || loop {
let job = {
let mut q = jobs.lock().unwrap();
q.pop() // lock released immediately
};
match job { Some(j) => run(j), None => break }
}));
}Popping under a short lock and processing outside it is the pattern that keeps N workers busy without serialising on the mutex.
7. Atomics instead of a mutex for a counter
use std::sync::atomic::{AtomicU64, Ordering};
let hits = Arc::new(AtomicU64::new(0));
let h = Arc::clone(&hits);
thread::spawn(move || { hits.fetch_add(1, Ordering::Relaxed); }).join().unwrap();
println!("{}", hits.load(Ordering::Relaxed));Relaxed is enough for a counter where only the final total matters; use Acquire/Release when the atomic guards publishing other data. A mutex around an integer is a common and unnecessary bottleneck.
Common mistakes and runtime errors
| Error / symptom | Cause | Fix |
|---|---|---|
E0277 closure may outlive the function | Borrowing a local in spawn | move, Arc, or thread::scope |
E0373 closure may outlive borrowed value | Missing move | Add move |
E0277 Rc cannot be sent between threads | Non-atomic refcount | Arc |
| Channel loop never exits | A sender is still alive | drop(tx) after cloning |
send returns Err(SendError) | Receiver dropped | Handle the error, stop producing |
| Deadlock with no CPU usage | Lock held across a blocking call, or lock order | Shorten lock scope, consistent order |
PoisonError on every lock() | A thread panicked while holding it | into_inner() and validate |
| Counter is wrong | Each thread cloned the value, not the Arc | Clone the Arc, mutate through the lock |
join() never returns | A worker thread is blocked forever | Timeouts, bounded queues |
E0716 joining a scoped handle twice | JoinHandle consumed by join | Join once, store the result |
deadlock on a bounded channel | Producer blocked with capacity 0 and no consumer | sync_channel(0) is a rendezvous; use capacity ≥ 1 |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.