trpl-zh-cn/listings/ch20-web-server/listing-20-23/src/lib.rs

96 lines
2.0 KiB
Rust
Raw Normal View History

2023-01-16 17:34:52 +08:00
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
2022-02-06 16:43:51 +08:00
// ANCHOR: here
pub struct ThreadPool {
workers: Vec<Worker>,
2023-01-16 17:34:52 +08:00
sender: Option<mpsc::Sender<Job>>,
2022-02-06 16:43:51 +08:00
}
// --snip--
// ANCHOR_END: here
2023-01-16 17:34:52 +08:00
type Job = Box<dyn FnOnce() + Send + 'static>;
2022-02-06 16:43:51 +08:00
// ANCHOR: here
impl ThreadPool {
// ANCHOR_END: here
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
2023-01-16 17:34:52 +08:00
// ANCHOR: here
2022-02-06 16:43:51 +08:00
pub fn new(size: usize) -> ThreadPool {
2023-01-16 17:34:52 +08:00
// --snip--
// ANCHOR_END: here
2022-02-06 16:43:51 +08:00
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)));
}
2023-01-16 17:34:52 +08:00
// ANCHOR: here
ThreadPool {
workers,
sender: Some(sender),
}
2022-02-06 16:43:51 +08:00
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
2023-01-16 17:34:52 +08:00
self.sender.as_ref().unwrap().send(job).unwrap();
2022-02-06 16:43:51 +08:00
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
2023-01-16 17:34:52 +08:00
drop(self.sender.take());
2022-02-06 16:43:51 +08:00
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
2023-01-16 17:34:52 +08:00
// ANCHOR_END: here
2022-02-06 16:43:51 +08:00
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
2023-01-16 17:34:52 +08:00
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
2022-02-06 16:43:51 +08:00
let thread = thread::spawn(move || loop {
2023-01-16 17:34:52 +08:00
let job = receiver.lock().unwrap().recv().unwrap();
2022-02-06 16:43:51 +08:00
2023-01-16 17:34:52 +08:00
println!("Worker {id} got a job; executing.");
2022-02-06 16:43:51 +08:00
2023-01-16 17:34:52 +08:00
job();
2022-02-06 16:43:51 +08:00
});
Worker {
id,
thread: Some(thread),
}
}
}