Browse Source

Ferme correctement les thread

nas 1 year ago
parent
commit
1d3695edb0
3 changed files with 42 additions and 12 deletions
  1. 5
    1
      README.md
  2. 35
    8
      src/lib.rs
  3. 2
    3
      src/main.rs

+ 5
- 1
README.md View File

@@ -2,7 +2,11 @@
2 2
 
3 3
 ## Usage
4 4
 
5
-Mettre son token dans le fichier `src/main.rs`
5
+Mettre un token valid dans le fichier `src/main.rs`
6
+
7
+### Serveur Web
8
+
9
+Développer en se basant sur : https://doc.rust-lang.org/book/ch20-00-final-project-a-web-server.html
6 10
 
7 11
 ## Ressources
8 12
 

+ 35
- 8
src/lib.rs View File

@@ -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
 }

+ 2
- 3
src/main.rs View File

@@ -25,8 +25,6 @@ fn handle_connection(mut stream: TcpStream) {
25 25
         _ => ("HTTP/1.1 404 NOT FOUND", "pages/404.html"),
26 26
     };
27 27
 
28
-    // --snip--
29
-
30 28
     let contents = fs::read_to_string(filename).unwrap();
31 29
     let length = contents.len();
32 30
 
@@ -47,11 +45,12 @@ fn webserver() {
47 45
             handle_connection(stream);
48 46
         });
49 47
     }
48
+    println!("Shutting down.");
50 49
 }
51 50
 
52 51
 #[tokio::main]
53 52
 async fn main() -> Result<(), Box<dyn Error>> {
54
-    let server = "https://redmine.cli.coop";//https://api.coinstats.app/public/v1/coins/dogecoin
53
+    let server = "https://redmine.cli.coop";
55 54
     let token = "[TOKEN]";
56 55
     let target = "issues.json";
57 56
     let option = "limit=2";

Loading…
Cancel
Save