mirror of https://github.com/KaiserY/trpl-zh-cn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.0 KiB
96 lines
2.0 KiB
use std::{
|
|
sync::{mpsc, Arc, Mutex},
|
|
thread,
|
|
};
|
|
|
|
// ANCHOR: here
|
|
pub struct ThreadPool {
|
|
workers: Vec<Worker>,
|
|
sender: Option<mpsc::Sender<Job>>,
|
|
}
|
|
// --snip--
|
|
// ANCHOR_END: here
|
|
|
|
type Job = Box<dyn FnOnce() + Send + 'static>;
|
|
|
|
// 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.
|
|
// ANCHOR: here
|
|
pub fn new(size: usize) -> ThreadPool {
|
|
// --snip--
|
|
|
|
// ANCHOR_END: here
|
|
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)));
|
|
}
|
|
|
|
// ANCHOR: here
|
|
ThreadPool {
|
|
workers,
|
|
sender: Some(sender),
|
|
}
|
|
}
|
|
|
|
pub fn execute<F>(&self, f: F)
|
|
where
|
|
F: FnOnce() + Send + 'static,
|
|
{
|
|
let job = Box::new(f);
|
|
|
|
self.sender.as_ref().unwrap().send(job).unwrap();
|
|
}
|
|
}
|
|
|
|
impl Drop for ThreadPool {
|
|
fn drop(&mut self) {
|
|
drop(self.sender.take());
|
|
|
|
for worker in &mut self.workers {
|
|
println!("Shutting down worker {}", worker.id);
|
|
|
|
if let Some(thread) = worker.thread.take() {
|
|
thread.join().unwrap();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// ANCHOR_END: here
|
|
|
|
struct Worker {
|
|
id: usize,
|
|
thread: Option<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().unwrap().recv().unwrap();
|
|
|
|
println!("Worker {id} got a job; executing.");
|
|
|
|
job();
|
|
});
|
|
|
|
Worker {
|
|
id,
|
|
thread: Some(thread),
|
|
}
|
|
}
|
|
}
|