Concurrency with a Thread Pool

Fixed worker threads, a shared job queue, and clean shutdown.

Part 3 of 3Updated

Spawning a thread per connection works until someone opens ten thousand connections. A pool bounds the damage.

use std::sync::{mpsc, Arc, Mutex};
use std::thread;

pub struct ThreadPool {
    workers: Vec<thread::JoinHandle<()>>,
    sender: Option<mpsc::Sender<Job>>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

The receiver is wrapped in Arc<Mutex<..>>: Arc so every worker shares ownership, Mutex so only one worker pulls a job at a time. The compiler will not let you share it any other way — mpsc::Receiver isn’t Sync, and that fact is checked at compile time rather than discovered in production.

For shutdown, drop the sender. Every worker’s recv() then returns Err, the loop exits, and joining the handles completes. That’s the whole protocol — no shutdown flag needed.