Sub topic 13
Building a small worker pool
This chapter combines channels and shared state into one program: a fixed set of threads that pull jobs from a shared queue. It assumes you can spawn and join threads and use move closures. It also assumes you know mpsc::channel, cloning a Sender, and Arc<Mutex<T>>. If any of those feel shaky, review the earlier chapters first.
Why a pool
Spawning one thread per task is simple, but it has costs. Each OS thread reserves stack memory and takes time to create. If tasks arrive without limit, so do threads. A worker pool starts a fixed number of threads once and feeds them jobs through a queue. Idle workers wait for the next job.
A pool needs three things:
- A queue that holds jobs. This is an
mpscchannel. - A way for several workers to take from that queue. This is the shared state part.
- A shutdown signal. This is dropping the sender.
The problem: Receiver is not shareable
An mpsc channel has many producers and a single consumer. Sender can be cloned, but Receiver cannot. It also is not Sync, so several threads cannot borrow one Receiver at the same time.
To let many workers consume from one queue, wrap the receiver in a Mutex so only one worker can call recv at a time. Wrap that in an Arc so each worker can own a handle to it.
That fence is a placeholder. The real diagram follows.
A first pool
This program squares the numbers 1 to 6 on three workers. It uses two channels: one carries jobs to the workers and one carries results back.
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
fn main() {
let (job_tx, job_rx) = mpsc::channel::<u32>();
let job_rx = Arc::new(Mutex::new(job_rx));
let (result_tx, result_rx) = mpsc::channel::<u32>();
let mut handles = Vec::new();
for _ in 0..3 {
let job_rx = Arc::clone(&job_rx);
let result_tx = result_tx.clone();
handles.push(thread::spawn(move || loop {
let job = job_rx.lock().unwrap().recv();
match job {
Ok(n) => result_tx.send(n * n).unwrap(),
Err(_) => break,
}
}));
}
drop(result_tx);
for n in 1..=6 {
job_tx.send(n).unwrap();
}
drop(job_tx);
let mut results: Vec<u32> = result_rx.iter().collect();
results.sort();
for h in handles {
h.join().unwrap();
}
println!("{results:?}");
}It prints [1, 4, 9, 16, 25, 36].
How it works
Each worker loops forever. It locks the mutex, calls recv, and gets either a job (Ok(n)) or an error. The error means the channel is closed and empty, so the worker breaks out of its loop and the thread ends.
The recv call blocks while the queue is empty. A blocked worker holds the lock the whole time, so the other workers wait on the mutex rather than on the channel. That is fine. When a job arrives, the worker holding the lock receives it and releases the lock, and the next worker takes its turn waiting.
Shutdown depends on two drops
Two drop calls make the program finish:
drop(job_tx)closes the job channel. Once the queue is empty, every worker'srecvreturnsErr, and the workers exit. Without this drop, the workers wait forever andjoinnever returns.drop(result_tx)removes the main thread's own copy of the result sender. The workers hold the other clones. When they exit, the last sender is gone andresult_rx.iter()ends. Without this drop, thecollectcall never finishes.
Jobs finish in no fixed order, which is why the program sorts the results before printing.
The lock-lifetime trap
The line that takes a job is written in two statements for a reason:
let job = job_rx.lock().unwrap().recv();The MutexGuard returned by lock().unwrap() is a temporary. A temporary is dropped at the end of the statement that created it. Here that is the let, so the lock is released as soon as recv returns, before the job runs.
Compare this tempting variant:
while let Ok(n) = job_rx.lock().unwrap().recv() {
result_tx.send(n * n).unwrap();
}Temporaries in the scrutinee of while let (and of match and if let) live until the end of the whole body. This version holds the lock while the job runs. Only one worker can work at a time, and the other workers sit blocked on the mutex. The program still gives correct output, so nothing warns you. The pool is simply serial.
A reusable pool type
The first version hard-codes the job as a u32 and the work as squaring. A reusable pool accepts any closure. Because closures have different types, the queue stores them as boxed trait objects.
use std::sync::{mpsc, Arc, Mutex};
use std::thread::{self, JoinHandle};
type Job = Box<dyn FnOnce() + Send + 'static>;
struct ThreadPool {
workers: Vec<JoinHandle<()>>,
sender: Option<mpsc::Sender<Job>>,
}
impl ThreadPool {
fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (tx, rx) = mpsc::channel::<Job>();
let rx = Arc::new(Mutex::new(rx));
let workers = (0..size)
.map(|_| {
let rx = Arc::clone(&rx);
thread::spawn(move || loop {
let message = rx.lock().unwrap().recv();
match message {
Ok(job) => job(),
Err(_) => break,
}
})
})
.collect();
ThreadPool { workers, sender: Some(tx) }
}
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());
for worker in self.workers.drain(..) {
worker.join().unwrap();
}
}
}
fn main() {
let (result_tx, result_rx) = mpsc::channel();
{
let pool = ThreadPool::new(3);
for n in 1..=6u32 {
let result_tx = result_tx.clone();
pool.execute(move || {
result_tx.send(n * n).unwrap();
});
}
}
drop(result_tx);
let mut results: Vec<u32> = result_rx.iter().collect();
results.sort();
println!("{results:?}");
}Design points
- The trait bounds.
FnOncelets a job consume what it captured.Sendis required because the closure moves to another thread.'staticis required because the pool cannot know how long the caller's borrowed data would live, so closures must own what they use. Option<Sender<Job>>.Drop::droponly gets&mut self, so it cannot move the sender out of the struct.Option::takeswaps inNoneand gives back the sender, which is then dropped to close the channel.- Drop order. The sender is dropped first, so the workers see a closed channel. Then each worker is joined. Reversing this order would deadlock, because the workers would never be told to stop.
- Queued jobs still run. A closed channel still delivers every message already buffered. Dropping the pool therefore finishes all queued jobs before the threads exit. The block in
mainforces the pool to drop, and so to drain, before the results are read.
Failure modes
| Situation | What happens | Remedy |
|---|---|---|
| `job_tx` or `ThreadPool` never dropped | Workers block in `recv` forever and `join` hangs | Drop the sender before joining |
| Original `result_tx` kept alive | The result loop never ends | `drop(result_tx)` after cloning |
| Job holds the receiver lock while running | Workers run one at a time | Take the job in a separate `let` |
| A job panics | That worker thread dies and the pool shrinks | Catch it with `std::panic::catch_unwind`, or respawn the worker |
| Producer faster than workers | The unbounded queue grows without limit | Use `sync_channel` for backpressure |
A panicking job needs care. In the pool above, a panic inside job() happens after the lock was released, so the mutex is not poisoned. The worker thread ends, though, and join in Drop would then return Err and trigger unwrap. A production pool decides whether to log the failure, restart the worker, or propagate it.
Adding backpressure
The queue above is unbounded. If the main thread submits jobs faster than the workers finish them, memory use grows. Replacing mpsc::channel with mpsc::sync_channel(capacity) bounds the queue. execute then blocks when the queue is full, which slows the producer to the workers' pace. The sender type changes to SyncSender<Job>, and the rest of the code stays the same.
Where this pattern fits
The pool uses both tools from this tutorial for what each does best. A channel moves ownership of work between threads. The Arc<Mutex<_>> exists only to share the single receiving end. Workers never share the data they process. Each job moves into one worker, and the results move back through a channel. This is also the shape of the pool in the Rust Book, and of the work-queue crates that offer more features, such as rayon and threadpool. For CPU-bound data parallelism, prefer rayon over writing your own.
Exercise
In the first pool, a developer replaces the line let job = job_rx.lock().unwrap().recv(); and the match with while let Ok(n) = job_rx.lock().unwrap().recv() { result_tx.send(n * n).unwrap(); }. The output is still correct. What is wrong with the new version, and how does the lock-lifetime rule explain it?
Show answer
The temporary MutexGuard in the while let scrutinee lives until the end of the loop body, so the lock is held while the job runs. Only one worker can hold the lock at a time, so the others stay blocked on the mutex and the jobs run one after another. The output is correct but the pool gives no parallelism. Taking the job in a separate let statement drops the guard at the end of that statement.
Exercise
In the ThreadPool type, Drop first calls drop(self.sender.take()) and then joins the workers. What happens if you join the workers first, and why must sender be an Option?
Show answer
The workers are blocked in recv waiting for jobs, and the channel is still open because the pool's own sender is alive. They never exit, so join waits forever and the program deadlocks. sender must be an Option because drop receives &mut self and cannot move a field out. Option::take replaces it with None and returns the Sender, which can then be dropped to close the channel.
Exercise
Change the ThreadPool so that execute blocks when more than 4 jobs are waiting. Which channel type and which field type change?
Show answer
Use mpsc::sync_channel::<Job>(4) instead of mpsc::channel::<Job>(). The sender field changes from Option<mpsc::Sender<Job>> to Option<mpsc::SyncSender<Job>>. The worker loop and the Drop implementation stay the same, because SyncSender closes the channel when dropped and recv behaves the same way.