Skip to content

Commit 19f7f11

Browse files
committed
finish rust book
1 parent c933530 commit 19f7f11

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

rust/hello/src/lib.rs

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::{
55

66
pub struct ThreadPool {
77
workers: Vec<Worker>,
8-
sender: mpsc::Sender<Job>,
8+
sender: Option<mpsc::Sender<Job>>,
99
}
1010

1111
impl ThreadPool {
@@ -17,14 +17,27 @@ impl ThreadPool {
1717
for id in 0..size {
1818
workers.push(Worker::new(id, Arc::clone(&receiver)));
1919
}
20-
ThreadPool { workers, sender }
20+
ThreadPool {
21+
workers,
22+
sender: Some(sender),
23+
}
2124
}
2225
pub fn execute<F>(&self, f: F)
2326
where
2427
F: FnOnce() + Send + 'static,
2528
{
2629
let job = Box::new(f);
27-
self.sender.send(job).unwrap();
30+
self.sender.as_ref().unwrap().send(job).unwrap();
31+
}
32+
}
33+
34+
impl Drop for ThreadPool {
35+
fn drop(&mut self) {
36+
drop(self.sender.take());
37+
for worker in &mut self.workers.drain(..) {
38+
println!("Shutting down the worker {}", worker.id);
39+
worker.thread.join().unwrap();
40+
}
2841
}
2942
}
3043

@@ -37,9 +50,17 @@ impl Worker {
3750
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
3851
let thread = thread::spawn(move || {
3952
loop {
40-
let job = receiver.lock().unwrap().recv().unwrap();
41-
println!("Worker {id} got a job! Executing!");
42-
job();
53+
let msg = receiver.lock().unwrap().recv();
54+
match msg {
55+
Ok(job) => {
56+
println!("Worker {id} got a job! Executing!");
57+
job();
58+
}
59+
Err(_) => {
60+
println!("Worker {id} disconnected! Shutting down!");
61+
break;
62+
}
63+
};
4364
}
4465
});
4566
Worker { id, thread }

rust/hello/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use std::{
99
fn main() {
1010
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
1111
let pool = ThreadPool::new(4);
12-
for stream in listener.incoming() {
12+
for stream in listener.incoming().take(2) {
1313
let stream = stream.unwrap();
1414
pool.execute(|| handle_connection(stream));
1515
}

0 commit comments

Comments
 (0)