Browse Source

starting bits for a thread pool library. webserver tutorial now in the main docs, as of rust 1.19

jmelesky 7 years ago
parent
commit
f491df59f1
2 changed files with 74 additions and 2 deletions
  1. 22 2
      helloweb/src/bin/main.rs
  2. 52 0
      helloweb/src/lib.rs

+ 22 - 2
helloweb/src/main.rs → helloweb/src/bin/main.rs

@@ -3,16 +3,32 @@ use std::io::prelude::*;
 use std::net::TcpListener;
 use std::net::TcpStream;
 use std::fs::File;
+use std::thread;
+use std::time::Duration;
+
+extern crate helloweb;
+use helloweb::ThreadPool;
+
+
+// struct ThreadPool;
+// impl ThreadPool {
+//     fn new(size: u32) -> ThreadPool { ThreadPool }
+//     fn execute<F>(&self, f: F)
+//         where F: FnOnce() + Send + 'static {}
+// }
 
 
 fn main() {
     let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
+    let pool = ThreadPool::new(4);
 
     for stream in listener.incoming() {
         // "unwrap" means "just crash if there's an error"
         let stream = stream.unwrap();
 
-        handle_connection(stream);
+        pool.execute(|| {
+            handle_connection(stream);
+        });
     }
 }
 
@@ -25,10 +41,14 @@ fn handle_connection(mut stream: TcpStream) {
 
     stream.read(&mut buffer).unwrap();
 
-    let get = b"GET / HTTP/1.1\r\n";
+    let get =   b"GET / HTTP/1.1\r\n";
+    let sleep = b"GET /sleep HTTP/1.1\r\n";
 
     let (status_line, filename) = if buffer.starts_with(get) {
         ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+    } else if buffer.starts_with(sleep) {
+        thread::sleep(Duration::from_secs(5));
+        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
     } else {
         ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
     };

+ 52 - 0
helloweb/src/lib.rs

@@ -0,0 +1,52 @@
+use std::thread;
+
+
+pub struct ThreadPool {
+    workers: Vec<Worker>,
+}
+
+impl ThreadPool {
+    /// Create a new ThreadPool
+    ///
+    /// `size` is the number of threads in the pool.
+    ///
+    /// # Panics
+    ///
+    /// `new` will panic if the size is zero.
+    pub fn new(size: usize) -> ThreadPool {
+        assert!(size > 0);
+
+        let mut workers = Vec::with_capacity(size);
+
+        for id in 0..size {
+            workers.push(Worker::new(id));
+        }
+
+        ThreadPool {
+            workers
+        }
+    }
+
+    pub fn execute<F>(&self, f: F)
+        where
+        F: FnOnce() + Send + 'static
+    {
+    }
+}
+
+
+struct Worker {
+    id: usize,
+    thread: thread::JoinHandle<()>,
+}
+
+impl Worker {
+    fn new(id: usize) -> Worker {
+        let thread = thread::spawn(|| {});
+
+        Worker {
+            id,
+            thread,
+        }
+    }
+}