Fearless Concurrency
How Rust prevents data races at compile time — threads and move closures, Send and Sync, Arc with Mutex and RwLock, atomics, channels, scoped threads, and data parallelism with Rayon.
In most languages, concurrency bugs — data races, unsynchronised access, forgetting a lock — surface as rare, unreproducible production failures. Rust turns most of them into compile errors. The same ownership and borrowing rules that ensure memory safety (Borrowing) also prevent data races, because a data race requires two threads accessing the same data with at least one writing — and Rust only allows mutation through exclusive access.
Threads
use std::thread;
let data = vec![1, 2, 3];
let handle = thread::spawn(move || { // move: the closure takes ownership of data
let sum: i32 = data.iter().sum();
sum
});
let total = handle.join().unwrap(); // wait; join returns the thread's resultWithout move, the closure would borrow data — but the new thread might outlive the function that owns data, so the compiler rejects it:
error[E0373]: closure may outlive the current function, but it borrows `data`, which is owned by the current function
help: to force the closure to take ownership of `data`, use the `move` keywordScoped threads
When threads are guaranteed to finish before the scope ends, they can borrow local data:
let mut counts = [0usize; 4];
let words = vec!["a", "bb", "ccc"];
thread::scope(|s| {
for (i, slot) in counts.iter_mut().enumerate() {
let words = &words;
s.spawn(move || { *slot = words.iter().filter(|w| w.len() > i).count(); });
}
}); // all spawned threads are joined hereSend and Sync
Two marker traits encode thread safety in the type system; the compiler implements them automatically based on a type's contents:
| Trait | Meaning | Not implemented by |
|---|---|---|
Send | Ownership can be moved to another thread | Rc<T> (non-atomic refcount), raw pointers |
Sync | &T can be shared between threads (T is Sync iff &T is Send) | Cell<T>, RefCell<T> (unsynchronised interior mutability), Rc<T> |
thread::spawn requires its closure to be Send + 'static. Try to send an Rc and you get a compile error, not a corrupted refcount at 3 a.m.:
error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safelyShared state: Arc + Mutex
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 || {
for _ in 0..1000 {
let mut n = counter.lock().unwrap(); // MutexGuard: access only while locked
*n += 1;
} // guard dropped → unlocked automatically
}));
}
for h in handles { h.join().unwrap(); }
println!("{}", *counter.lock().unwrap()); // always 8000Key design point: in Rust the mutex owns the data it protects. You physically can't touch the data without holding the lock, and you can't forget to unlock (the guard's Drop does it). Compare with Java/C, where the lock and the data are separate and the association is only a convention (Java concurrency).
| Tool | Use |
|---|---|
Mutex<T> | Exclusive access |
RwLock<T> | Many readers or one writer |
AtomicUsize, AtomicBool… | Lock-free counters and flags |
OnceLock / LazyLock | Thread-safe one-time initialisation |
Condvar, Barrier | Coordination |
(.lock() returns a Result because a mutex becomes poisoned if a thread panicked while holding it. The parking_lot crate offers faster locks without poisoning.)
Message passing: channels
"Do not communicate by sharing memory; share memory by communicating." Channels transfer ownership of values between threads:
use std::sync::mpsc; // multi-producer, single-consumer
use std::thread;
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
for job in 0..5 {
tx.send(format!("worker {id} finished job {job}")).unwrap();
}
});
}
drop(tx); // close the original sender so the loop below ends
for msg in rx { // iterates until all senders are dropped
println!("{msg}");
}Once a value is sent, the sender can't use it anymore (it's moved) — so there's no way to accidentally mutate data another thread is reading. Use mpsc::sync_channel(n) for a bounded channel with backpressure; the crossbeam-channel and flume crates add multi-consumer channels and select!.
Data parallelism with Rayon
For CPU-bound work over collections, Rayon turns sequential iterators into parallel ones with a work-stealing thread pool — often a one-word change:
use rayon::prelude::*;
let total: u64 = (1..=10_000_000u64)
.into_par_iter() // instead of into_iter()
.filter(|n| n % 3 == 0)
.map(|n| n * n)
.sum();
images.par_iter_mut().for_each(|img| img.apply_blur(2.0));And it's still race-free: if your closure tried to mutate shared state without synchronisation, it wouldn't compile.
Choosing
| Problem | Tool |
|---|---|
| CPU-bound work over collections | Rayon |
| Independent tasks with results | thread::spawn / scoped threads + join |
| Pipeline or producer–consumer | Channels |
| Shared mutable state | Arc<Mutex<T>>, Arc<RwLock<T>>, atomics |
| Thousands of concurrent I/O operations | async/await with Tokio (Async Rust) |
- Ownership and borrowing rules prevent data races at compile time.
- move closures transfer ownership into threads; scoped threads can borrow.
- Send (can move between threads) and Sync (can share references) are checked automatically; Rc and RefCell are neither.
- A Mutex owns its data; the guard unlocks on drop — you can't forget or bypass the lock.
- Channels transfer ownership; Rayon parallelises iterators safely.
- Deadlocks and logic races are still possible.
QWhat do Send and Sync mean in Rust?hard
They are auto-implemented marker traits describing thread safety. A type is Send if ownership of it can be transferred to another thread, and Sync if it's safe for multiple threads to hold shared references to it simultaneously (T is Sync exactly when &T is Send). Rc is neither because its reference count isn't atomic; RefCell is Send but not Sync because its borrow tracking isn't synchronised. APIs like thread::spawn require Send, so misuse is a compile error.