Module 17 Exercises — Fearless Concurrency
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to state:
- what a data race is, in one sentence;
- why
Arc<Mutex<T>>needs both parts; - why the compiler rejects
Rcacross threads, in terms of whatRcdoes internally.
Do the drill that tries Rc between threads and read the full error before fixing it. The compiler names Send, and seeing where that requirement comes from makes the rest of the module straightforward.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 17.1 — Spawn and join
Spawn 5 threads, each returning id * id, collect the results in order, and print them.
Solution
use std::thread;
fn main() {
let handles: Vec<_> = (0..5)
.map(|id| thread::spawn(move || id * id))
.collect();
let results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
println!("{results:?}"); // [0, 1, 4, 9, 16]
}Collecting the handles first is essential — spawning and joining in the same loop serializes everything.
🟢 Exercise 17.2 — Diagnose the error
Explain why this fails and fix it two ways:
use std::rc::Rc;
use std::thread;
let data = Rc::new(vec![1, 2, 3]);
let d = Rc::clone(&data);
thread::spawn(move || println!("{d:?}")).join().unwrap();Solution
Rc is not Send: its reference count is a plain integer, so two threads could increment
it concurrently and lose an update, causing a use-after-free.
// fix 1: Arc
use std::sync::Arc;
let data = Arc::new(vec![1, 2, 3]);
let d = Arc::clone(&data);
thread::spawn(move || println!("{d:?}")).join().unwrap();
// fix 2: scoped threads with a borrow
let data = vec![1, 2, 3];
std::thread::scope(|s| { s.spawn(|| println!("{data:?}")); });Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 17.3 — Producer/consumer pipeline
Build a pipeline: 3 producer threads each send 5 numbers; one consumer sums everything and prints the total. Ensure the program terminates.
Solution
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let producers: Vec<_> = (0..3).map(|id| {
let tx = tx.clone();
thread::spawn(move || {
for i in 0..5 {
tx.send(id * 10 + i).unwrap();
}
})
}).collect();
drop(tx); // critical: otherwise `for x in rx` never ends
let total: i32 = rx.iter().sum();
for p in producers { p.join().unwrap(); }
println!("total = {total}");
}🟡 Exercise 17.4 — Shared word counter
Given 4 threads each processing a chunk of text, build a shared
Arc<Mutex<HashMap<String, usize>>> word-frequency map and print the top 3 words.
Solution
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let chunks = vec![
"the quick brown fox",
"the lazy dog sleeps",
"the fox jumps high",
"a quick brown dog",
];
let counts: Arc<Mutex<HashMap<String, usize>>> = Arc::new(Mutex::new(HashMap::new()));
let handles: Vec<_> = chunks.into_iter().map(|chunk| {
let counts = Arc::clone(&counts);
thread::spawn(move || {
// Count locally first, then merge once — minimizes lock contention.
let mut local: HashMap<&str, usize> = HashMap::new();
for w in chunk.split_whitespace() { *local.entry(w).or_insert(0) += 1; }
let mut global = counts.lock().unwrap();
for (w, n) in local {
*global.entry(w.to_string()).or_insert(0) += n;
}
})
}).collect();
for h in handles { h.join().unwrap(); }
let map = counts.lock().unwrap();
let mut pairs: Vec<_> = map.iter().collect();
pairs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
println!("{:?}", &pairs[..3]);
}The local-then-merge pattern is the important lesson: holding a global lock inside a hot loop destroys parallelism.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 17.5 — Thread pool
Implement a ThreadPool with new(size) and execute<F: FnOnce() + Send + 'static>(f: F),
using Arc<Mutex<mpsc::Receiver<Job>>> for work distribution and a graceful Drop that
joins all workers.
Solution
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
type Job = Box<dyn FnOnce() + Send + 'static>;
struct Worker { id: usize, thread: Option<thread::JoinHandle<()>> }
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
// Lock, receive, and UNLOCK before running the job.
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => {
println!("worker {id} got a job");
job();
}
Err(_) => {
println!("worker {id} shutting down");
break;
}
}
});
Worker { id, thread: Some(thread) }
}
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
impl ThreadPool {
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let workers = (0..size).map(|id| Worker::new(id, Arc::clone(&receiver))).collect();
ThreadPool { workers, sender: Some(sender) }
}
pub fn execute<F>(&self, f: F)
where F: FnOnce() + Send + 'static {
self.sender.as_ref().unwrap().send(Box::new(f)).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.sender.take()); // closes the channel -> workers see Err
for worker in &mut self.workers {
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
fn main() {
let pool = ThreadPool::new(4);
for i in 0..8 {
pool.execute(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
println!("task {i} done");
});
}
} // Drop runs here: closes the channel and joins every workerTwo subtleties worth internalizing:
let message = receiver.lock().unwrap().recv();— the temporaryMutexGuarddrops at the end of the statement, beforejob()runs. If you wrotewhile let Ok(job) = receiver.lock().unwrap().recv() { job(); }, the guard would live for the whole loop body and your pool would execute one job at a time.Optiononsenderandthreadexists soDropcantake()them — you can't move out of&mut self.
Self-check
- What three conditions define a data race, and which one do Rust's borrow rules break?
- What's the difference between
SendandSync? - Why is
Rcnot usable across threads? - Why does forgetting
drop(tx)hang a program? - When is
RwLocka worse choice thanMutex?
Answers
- Multiple accesses to one location, at least one write, no synchronization. Rust prevents having a writer and any other accessor simultaneously.
Send= ownership can move to another thread;Sync=&Tcan be shared across threads.- Its reference count is non-atomic, so concurrent clones/drops could corrupt it — hence
Rc: !Send. - The receiver's iterator only ends when all senders are dropped; the original
txkeeps it alive forever. - Under write-heavy workloads, where the extra bookkeeping costs more than it saves.
Next: Module 18 — Async Rust
