parent
a0ef441eea
commit
b20735e2e9
@ -0,0 +1,67 @@
|
|||||||
|
use std::{
|
||||||
|
sync::{mpsc, Arc, Mutex},
|
||||||
|
thread,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct ThreadPool {
|
||||||
|
workers: Vec<Worker>,
|
||||||
|
sender: mpsc::Sender<Job>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThreadPool {
|
||||||
|
/// Create a new ThreadPool.
|
||||||
|
///
|
||||||
|
/// The size is the number of workers in the pool.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// The `new` function will panic if the size is zero.
|
||||||
|
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 {
|
||||||
|
// create some workers and store them in the vector
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Job = Box<dyn FnOnce() + Send + 'static>;
|
||||||
|
|
||||||
|
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 job = receiver
|
||||||
|
.lock()
|
||||||
|
.expect("Mutex poisoned; bailing out.")
|
||||||
|
.recv()
|
||||||
|
.expect("Failed to receive job.");
|
||||||
|
|
||||||
|
println!("Worker {} got a job; executing.", id);
|
||||||
|
|
||||||
|
job();
|
||||||
|
});
|
||||||
|
|
||||||
|
Worker { id, thread }
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in new issue