|
@@ -5,7 +5,7 @@ use std::{
|
5
|
5
|
|
6
|
6
|
pub struct ThreadPool {
|
7
|
7
|
workers: Vec<Worker>,
|
8
|
|
- sender: mpsc::Sender<Job>,
|
|
8
|
+ sender: Option<mpsc::Sender<Job>>
|
9
|
9
|
}
|
10
|
10
|
|
11
|
11
|
type Job = Box<dyn FnOnce() + Send + 'static>;
|
|
@@ -31,7 +31,10 @@ impl ThreadPool {
|
31
|
31
|
workers.push(Worker::new(id, Arc::clone(&receiver)));
|
32
|
32
|
}
|
33
|
33
|
|
34
|
|
- ThreadPool { workers, sender }
|
|
34
|
+ ThreadPool {
|
|
35
|
+ workers,
|
|
36
|
+ sender: Some(sender)
|
|
37
|
+ }
|
35
|
38
|
}
|
36
|
39
|
|
37
|
40
|
pub fn execute<F>(&self, f: F)
|
|
@@ -39,26 +42,50 @@ impl ThreadPool {
|
39
|
42
|
F: FnOnce() + Send + 'static,
|
40
|
43
|
{
|
41
|
44
|
let job = Box::new(f);
|
|
45
|
+ self.sender.as_ref().unwrap().send(job).unwrap();
|
|
46
|
+ }
|
|
47
|
+}
|
|
48
|
+
|
|
49
|
+impl Drop for ThreadPool {
|
|
50
|
+ fn drop(&mut self) {
|
|
51
|
+ drop(self.sender.take());
|
42
|
52
|
|
43
|
|
- self.sender.send(job).unwrap();
|
|
53
|
+ for worker in &mut self.workers {
|
|
54
|
+ println!("Shutting down worker {}", worker.id);
|
|
55
|
+
|
|
56
|
+ if let Some(thread) = worker.thread.take() {
|
|
57
|
+ thread.join().unwrap();
|
|
58
|
+ }
|
|
59
|
+ }
|
44
|
60
|
}
|
45
|
61
|
}
|
46
|
62
|
|
47
|
63
|
struct Worker {
|
48
|
64
|
id: usize,
|
49
|
|
- thread: thread::JoinHandle<()>,
|
|
65
|
+ thread: Option<thread::JoinHandle<()>>,
|
50
|
66
|
}
|
51
|
67
|
|
52
|
68
|
impl Worker {
|
53
|
69
|
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
54
|
70
|
let thread = thread::spawn(move || loop {
|
55
|
|
- let job = receiver.lock().unwrap().recv().unwrap();
|
|
71
|
+ let message = receiver.lock().unwrap().recv();
|
56
|
72
|
|
57
|
|
- println!("Worker {id} got a job; executing.");
|
|
73
|
+ match message {
|
|
74
|
+ Ok(job) => {
|
|
75
|
+ println!("Worker {id} got a job; executing.");
|
58
|
76
|
|
59
|
|
- job();
|
|
77
|
+ job();
|
|
78
|
+ }
|
|
79
|
+ Err(_) => {
|
|
80
|
+ println!("Worker {id} disconnected; shutting down.");
|
|
81
|
+ break;
|
|
82
|
+ }
|
|
83
|
+ }
|
60
|
84
|
});
|
61
|
85
|
|
62
|
|
- Worker { id, thread }
|
|
86
|
+ Worker {
|
|
87
|
+ id,
|
|
88
|
+ thread: Some(thread),
|
|
89
|
+ }
|
63
|
90
|
}
|
64
|
91
|
}
|