Implement a worker pool by defining a ThreadPool struct that manages a Vec<Worker> and uses an mpsc channel to distribute Job closures to threads.
use std::{sync::{Arc, Mutex, mpsc}, thread};
type Job = Box<dyn FnOnce() + Send + 'static>;
pub struct ThreadPool {
workers: Vec<Worker>,
sender: 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 mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => job(),
Err(_) => break,
}
});
Worker { id, thread }
}
}
- Define the
Jobtype alias as a boxed closure that isSendand lives for'static. - Create the
ThreadPoolstruct holding a vector ofWorkerand anmpsc::Sender. - Implement
ThreadPool::newto create a channel, wrap the receiver inArc<Mutex<>>, and spawn workers. - Implement
ThreadPool::executeto box the closure and send it through the sender. - Define the
Workerstruct to hold an ID and aJoinHandle. - Implement
Worker::newto spawn a thread that loops, locks the receiver, and executes received jobs.