Module 17 — Fearless Concurrency
Goal
Threads, channels and Arc<Mutex<T>> — and the Send/Sync traits that turn data races from a debugging nightmare into a compile error.
Start here — what this module is really about
"Fearless concurrency" is a marketing phrase with a precise technical meaning, and it is worth unpacking before the code.
A data race happens when two threads touch the same memory at the same time and at least one is writing. The result is undefined: torn values, lost updates, corruption that shows up somewhere else entirely. What makes these the worst bugs in the industry is not the damage — it is that they are timing dependent. They appear under load, on one machine, once a week, and vanish when you attach a debugger.
Most languages address this with discipline: use locks, be careful, review thoroughly. Rust addresses it with the borrow checker you already know. Look at the definition again — two accesses, same data, one writing — and compare it with module 05's rule: many readers or one writer, never both. It is the same rule. Rust simply applies it across threads as well as within one.
That is the whole trick, and the consequence is unusual: a data race in safe Rust is a compile error. Not a race that might be caught in testing — a program that does not build.
Two traits make it work, and you will see them in error messages:
Send— this type can be moved to another thread.Sync— this type can be shared (by reference) between threads.
Almost every type is both automatically; the compiler works it out. The ones that are not — Rc, RefCell — are exactly the types whose internal bookkeeping is not safe against concurrent access, which is why the compiler stops you and points at the thread-safe equivalent.
The one sentence to remember: the borrowing rules you already know, applied across threads, turn data races from a debugging nightmare into a compile error.
Learning objectives
- Spawn threads and join them
- Move data into threads safely
- Use channels for message passing
- Use
Arc<Mutex<T>>andRwLockfor shared state - Explain
SendandSyncand why data races are compile errors - Use atomics, scoped threads, and
rayonfor data parallelism
17.1 Why "fearless"
A data race requires three things simultaneously: two or more pointers to the same data, at least one writing, and no synchronization. The borrowing rules from module 05 make that combination impossible to express in safe Rust — the same rules that prevent iterator invalidation in single-threaded code prevent data races in multi-threaded code, for free.
The result: concurrency bugs that are runtime heisenbugs in other languages are compile errors in Rust. You still have to reason about deadlocks and logical races, but not about torn reads or memory corruption.
Analogy — the shared spreadsheet, again
Data races are the hardest bugs in the industry because they are the ones that do not reproduce: two threads touched the same cell in an order that happened once, on a Tuesday, under load. Rust's move is that it already has a rule about many readers or one writer — the same rule from module 05, now applied across threads. 'Fearless' means the race becomes a compile error you fix in the morning, not an incident you cannot reproduce at 3am.
17.2 Threads
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("spawned: {i}");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("main: {i}");
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap(); // wait for the thread; without this, main may exit first
}join() returns Result<T, Box<dyn Any>> — Err if the thread panicked. T is whatever
the closure returned:
let handle = thread::spawn(|| (1..=100).sum::<u32>());
let total = handle.join().unwrap();
println!("{total}"); // 5050move closures are usually required
let v = vec![1, 2, 3];
// ❌ the thread might outlive `v`
// thread::spawn(|| println!("{v:?}"));
thread::spawn(move || println!("{v:?}")).join().unwrap(); // ✅The compiler doesn't know when the thread will run, so it requires ownership transfer.
Scoped threads (Rust 1.63+)
When you know the threads finish before the borrowed data dies, scoped threads let you borrow:
use std::thread;
fn main() {
let mut data = vec![1, 2, 3];
thread::scope(|s| {
s.spawn(|| println!("read: {data:?}")); // borrow, no move
s.spawn(|| println!("also read: {}", data.len()));
}); // all threads joined here
data.push(4); // ✅ borrows are over
println!("{data:?}");
}This removes most of the Arc boilerplate for fork-join workloads.
move and join, and why threads need them
use std::thread;
let data = vec![1, 2, 3];
let handle = thread::spawn(move || { // `move` is mandatory here
println!("{data:?}");
});
handle.join().unwrap(); // wait for it to finishTwo pieces that are not optional, and the reasons behind both:
Why move. A spawned thread may outlive the function that created it. Without move, the closure would borrow data — and the borrow checker cannot prove that data will still exist when the thread eventually runs. move transfers ownership into the closure, so the thread owns what it uses. Omit it and you get closure may outlive the current function, which is owned by the current function, which is the compiler describing exactly this.
Why join. spawn returns a handle and returns immediately. If main ends first, the process exits and the thread is killed mid-work. .join() blocks until it finishes, and hands back its result — which is also how a panic inside a thread reaches you, as an Err.
One useful consequence of ownership here: once data has moved into the thread, the original scope cannot use it. There is no "the main thread might also touch it" hazard to reason about, because the language made it impossible.
17.3 Message passing
Note
"Do not communicate by sharing memory; instead, share memory by communicating." — Go proverb that Rust also takes seriously.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel(); // multiple producer, single consumer
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(format!("hello from {id}")).unwrap();
});
}
drop(tx); // drop the original so rx knows when to stop
for received in rx { // iterates until all senders are dropped
println!("{received}");
}
}Key points:
sendmoves the value into the channel — ownership transfers to the receiver, so there's no aliasing to worry about.rx.recv()blocks;rx.try_recv()doesn't.- Iterating
rxends when every sender is dropped. Forgetting todrop(tx)is the #1 cause of a program that hangs forever. mpsc::sync_channel(n)gives a bounded channel with backpressure.
Analogy — the pneumatic tube
Message passing is the pneumatic tube in an old department store: you put the docket in the capsule, send it, and it is no longer on your counter. Ownership travelling down the channel is what makes this safe — there is no shared copy left behind to disagree about, which is why the classic advice is to send data rather than share it.
17.4 Shared state
Mutex<T>
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
})); // lock released when `num` drops
}
for h in handles { h.join().unwrap(); }
println!("result: {}", *counter.lock().unwrap()); // 10
}Notice the design: in Rust, the mutex owns the data. You cannot access the value
without acquiring the lock, because lock() is the only way to get a reference. Compare
with C or Java, where the mutex and the data it protects are related only by convention
and a comment.
lock() returns Result because a mutex becomes poisoned if a thread panics while
holding it — a signal that the protected invariant may be broken.
Scope your locks:
{
let mut guard = data.lock().unwrap();
guard.push(1);
} // released here
expensive_computation(); // not holding the lockArc<T>
Arc is Rc with atomic reference counting — safe to share across threads.
let data = Arc::new(vec![1, 2, 3]);
let d2 = Arc::clone(&data);
thread::spawn(move || println!("{d2:?}")).join().unwrap();Use Rc in single-threaded code (faster), Arc when crossing threads. Arc<T> alone
gives shared immutable access; Arc<Mutex<T>> gives shared mutable access.
RwLock<T>
Many readers or one writer:
use std::sync::{Arc, RwLock};
let config = Arc::new(RwLock::new(String::from("v1")));
{
let r1 = config.read().unwrap();
let r2 = config.read().unwrap(); // ✅ concurrent readers
println!("{r1} {r2}");
}
{
let mut w = config.write().unwrap(); // exclusive
*w = String::from("v2");
}Use for read-heavy data (configuration, caches). For write-heavy workloads a plain
Mutex is usually faster because RwLock has more bookkeeping.
Atomics
For single values, skip the lock entirely:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
let counter = Arc::new(AtomicUsize::new(0));
let mut handles = vec![];
for _ in 0..10 {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || { c.fetch_add(1, Ordering::SeqCst); }));
}
for h in handles { h.join().unwrap(); }
println!("{}", counter.load(Ordering::SeqCst));Ordering::SeqCst is the strongest and safest default. Weaker orderings (Relaxed,
Acquire, Release) are faster but require real understanding of the memory model — use
SeqCst until you can explain why you need less.
Arc<Mutex<T>> — what each layer is for
This combination looks intimidating and is actually two independent problems stacked:
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter); // one handle per thread
handles.push(thread::spawn(move || {
let mut n = counter.lock().unwrap(); // wait for the key
*n += 1;
})); // key returned automatically here
}
for h in handles { h.join().unwrap(); }
println!("{}", *counter.lock().unwrap()); // 10, every timePeel the layers:
Mutex<T>solves "only one at a time".lock()waits until nothing else holds it, then hands back a guard you can use to reach the value. When the guard is dropped, the lock is released automatically — so the classic "forgot to unlock" bug cannot be written. This isDropfrom module 04 doing real work.Arc<T>solves "who owns it". Ten threads all need the mutex to stay alive, and none of them can be the single owner.ArcisRcwith a thread-safe counter — atomic, hence the name.Rchere would be a compile error, and that error is the compiler protecting you from a genuinely racy counter.
Two things to remember once it works:
lock()returns aResult, because a thread that panics while holding the lock poisons it..unwrap()is common and honest here: it says "if a thread died mid-update, this data is suspect and I want to stop".- Keep the guard's scope tight. Holding a lock across a long operation is how a fast program becomes a slow one, and holding it across an
.await(module 18) is how it deadlocks.
Analogy — the one key to the meeting room
A Mutex is a room with a single key on a hook. To use the room you take the key; while you hold it nobody else gets in; when you leave, the key goes back on the hook automatically — Rust hands it back when the guard is dropped, so the classic 'forgot to unlock' bug has nowhere to live. Arc<Mutex<T>> is that room in a shared building: the counter on the door keeps the building standing while anyone still has business there.
17.5 Send and Sync
Two marker traits, automatically implemented, that encode the whole thread-safety story:
Send: ownership of the type can be transferred to another thread.Sync:&Tcan be shared between threads (equivalently,T: Synciff&T: Send).
| Type | Send | Sync | Why |
|---|---|---|---|
i32, String, Vec<T> | ✅ | ✅ | plain data |
Rc<T> | ❌ | ❌ | non-atomic refcount would race |
Arc<T> | ✅ | ✅ | atomic refcount |
RefCell<T> | ✅ | ❌ | runtime borrow flags aren't atomic |
Mutex<T> | ✅ | ✅ | that's its job |
MutexGuard | ❌ | ✅ | must be released on the locking thread |
| raw pointers | ❌ | ❌ | no guarantees |
thread::spawn requires F: Send + 'static, which is why the compiler rejects passing an
Rc into a thread:
error[E0277]: `Rc<i32>` cannot be sent between threads safely
note: required because it appears within the type ...
help: within this `[closure]`
That error is Rust telling you, at compile time, that you nearly wrote a refcount race.
17.6 Data parallelism with rayon
[dependencies]
rayon = "1"use rayon::prelude::*;
fn main() {
let v: Vec<u64> = (0..10_000_000).collect();
let sum: u64 = v.iter().sum(); // sequential
let sum: u64 = v.par_iter().sum(); // parallel — same result
let squares: Vec<u64> = v.par_iter().map(|x| x * x).collect();
let mut data = vec![5, 2, 9, 1];
data.par_sort();
}Change iter() to par_iter() and rayon distributes the work across a thread pool with
work stealing. Because the borrow checker already guarantees the closure doesn't mutate
shared state unsafely, this transformation is safe by construction — that's the payoff of
everything in modules 4, 5, and 17.
Rayon is the right first tool for CPU-bound parallelism. Reach for raw threads only when you need long-lived workers or specific scheduling.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| thread | An independent line of execution within your process. |
| data race | Two threads touching the same memory, at least one writing, unsynchronised. |
spawn | Starting a new thread. |
join | Waiting for a thread to finish and collecting its result. |
move closure | A closure that takes ownership of what it captures — required for threads. |
| channel | A one-way pipe for sending values between threads (mpsc). |
mpsc | Multiple producer, single consumer — the standard library's channel. |
Mutex<T> | Mutual exclusion: only one thread may access the value at a time. |
| lock guard | The value lock() returns; the lock is held until it is dropped. |
| poisoning | A mutex marked suspect because a thread panicked while holding it. |
Arc<T> | Atomically reference-counted shared ownership — Rc for threads. |
Send | This type can be moved to another thread. |
Sync | This type can be shared by reference between threads. |
| deadlock | Two threads each waiting for a lock the other holds. Nothing progresses. |
rayon | A crate turning .iter() into .par_iter() for effortless data parallelism. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
closure may outlive the current function | The thread closure borrows instead of owning. | Add move before the ` |
Rc<T> cannot be sent between threads safely | Rc's counter is not thread-safe. | Use Arc instead. |
RefCell<T> cannot be shared between threads safely | RefCell is not Sync. | Use Mutex (or RwLock) instead. |
| The program hangs forever | A deadlock, or a join on a thread waiting for something. | Check for two locks taken in different orders, and for a guard held longer than intended. |
PoisonError | Another thread panicked while holding this lock. | Fix that panic. The poison is a symptom, not the bug. |
| Results differ between runs | Threads finishing in a different order. | Order is never guaranteed — collect results and sort, or use a channel. |
Now make it stick: work through the drills for this module, then carry on to Module 18 — Async Rust.
