Sub topic 13
Building a small worker pool
This chapter assumes you know thread::spawn and join, move closures, mpsc channels, and Arc<Mutex<T>>. It combines them into a worker pool: a fixed set of threads that pull jobs from one queue.
Why a pool
Spawning one thread per task is simple, but each OS thread costs memory and scheduling time. A pool starts a fixed number of workers once. Jobs wait in a queue, and each idle worker takes the next one.
The design needs two channels:
- A job channel carries work from the main thread to the workers.
- A result channel carries answers from the workers back to the main thread.
The problem with one Receiver
mpsc means multiple producer, single consumer. Receiver cannot be cloned, so three workers cannot each hold a copy. The fix is to wrap the receiver in Arc<Mutex<_>>. Arc gives every worker ownership of the same receiver. Mutex ensures only one worker calls recv at a time.
The Sender for results, by contrast, can be cloned, so each worker gets its own.
The full program
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 clones the
Arcand aresult_tx, then moves both into its closure. - Inside the loop,
job_rx.lock().unwrap().recv()locks the mutex and blocks until a job arrives. The lock guard is a temporary, so it is dropped at the end of thatletstatement. Other workers can then take the next job while this one computes. Ok(n)means a job arrived. The worker squares it and sends the answer.Err(_)means the job channel is closed and empty. The worker breaks out of its loop and the thread ends.
Shutting down
Shutdown relies on channel closure, with no special "stop" message. There are two drops, and both matter.
drop(job_tx)closes the job channel. Once the queue is empty, every worker'srecvreturnsErr, and the workers exit.drop(result_tx)removes the main thread's own result sender. The workers' clones are dropped when the threads end. Only then doesresult_rx.iter()stop. Without this drop, the collect would block forever.
Things to notice
- Results arrive in any order, because workers finish at different times. The program sorts them before printing.
- The mutex only guards the wait for the next job. It does not guard the computation.
- The job channel is unbounded. If jobs arrive faster than the workers can handle them, the queue grows without limit. Replacing
channelwithsync_channeladds backpressure, sosendblocks when the queue is full.
Exercise
In the worker pool, what happens if you remove drop(result_tx) from main but keep everything else? Why?
Show answer
The program hangs. The workers exit and drop their clones of result_tx, but the original result_tx in main is still alive. The result channel is never disconnected, so result_rx.iter() keeps waiting for more messages and never ends.
Exercise
Why must the workers share the job Receiver through Arc<Mutex<_>> instead of each getting a clone?
Show answer
Receiver does not implement Clone, because mpsc allows only one consumer. Arc lets all workers own the same receiver, and Mutex makes sure only one of them calls recv at a time.