Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readRust
#Rust#Concurrency#Multithreading
3D illustration of worker thread lanes pushing messages through an mpsc pipe into a receiver guarded by a Mutex

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

rust
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:

rust
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 parent

Bounded channels and timeouts:

rust
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

PrimitiveSharing modelThread safeBlockingTypical use
thread::spawnOwned closureSend + 'static requiredn/aCPU work, isolation
thread::scopeBorrowed closureBounded by scopeJoins on exitParallel reads of one buffer
Arc<Mutex<T>>Shared mutableYeslock() blocksCounters, caches, single-writer state
Arc<RwLock<T>>Shared, many readersYesread()/write()Read-heavy shared config
AtomicU64 etc.Shared, lock-freeYesNeverCounters, flags
mpsc::channelMessage passingYesrecv() blocksTask queues, fan-in
mpsc::sync_channel(n)BoundedYessend() blocks when fullBackpressure
Channel callOn emptyOn closed
recv()BlocksErr(RecvError)
try_recv()Err(TryRecvError::Empty)Err(TryRecvError::Disconnected)
recv_timeout(d)Waits up to d, then TimeoutDisconnected
iter() / forBlocks per itemEnds 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

rust
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 alive

rx 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

rust
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:

rust
thread::spawn(move || { let len = { let guard = s.lock().unwrap(); guard.len() }; // lock released here tx1.send(len).unwrap(); });

3. Two mutexes, opposite order

rust
// 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

rust
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

rust
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

rust
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

rust
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 / symptomCauseFix
E0277 closure may outlive the functionBorrowing a local in spawnmove, Arc, or thread::scope
E0373 closure may outlive borrowed valueMissing moveAdd move
E0277 Rc cannot be sent between threadsNon-atomic refcountArc
Channel loop never exitsA sender is still alivedrop(tx) after cloning
send returns Err(SendError)Receiver droppedHandle the error, stop producing
Deadlock with no CPU usageLock held across a blocking call, or lock orderShorten lock scope, consistent order
PoisonError on every lock()A thread panicked while holding itinto_inner() and validate
Counter is wrongEach thread cloned the value, not the ArcClone the Arc, mutate through the lock
join() never returnsA worker thread is blocked foreverTimeouts, bounded queues
E0716 joining a scoped handle twiceJoinHandle consumed by joinJoin once, store the result
deadlock on a bounded channelProducer blocked with capacity 0 and no consumersync_channel(0) is a rendezvous; use capacity ≥ 1

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.