From 4d4ba2d5f703969851742798e79e16333fb9ca9a Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sun, 19 Sep 2021 10:38:31 +0200 Subject: [PATCH] simple-http: Add scaffolding for thread pool implementation Turn into library crate. Add ThreadPool stub to src/lib. --- simple-http/src/{ => bin}/main.rs | 5 +++- simple-http/src/lib.rs | 40 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) rename simple-http/src/{ => bin}/main.rs (93%) create mode 100644 simple-http/src/lib.rs diff --git a/simple-http/src/main.rs b/simple-http/src/bin/main.rs similarity index 93% rename from simple-http/src/main.rs rename to simple-http/src/bin/main.rs index 0993075..ff3af27 100644 --- a/simple-http/src/main.rs +++ b/simple-http/src/bin/main.rs @@ -5,6 +5,8 @@ use std::net::TcpStream; use std::time::Duration; use std::{fs, str, thread}; +use simple_http::ThreadPool; + fn handle_connection(mut stream: TcpStream) { let mut buffer = [0; 1024]; @@ -61,9 +63,10 @@ fn handle_connection(mut stream: TcpStream) { fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); for stream in listener.incoming() { let stream = stream.unwrap(); - thread::spawn(|| handle_connection(stream)); + pool.execute(|| handle_connection(stream)); } } diff --git a/simple-http/src/lib.rs b/simple-http/src/lib.rs new file mode 100644 index 0000000..ff8bc4f --- /dev/null +++ b/simple-http/src/lib.rs @@ -0,0 +1,40 @@ +use std::thread; + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize) -> Worker { + Worker { id, thread: thread::spawn(|| {}) } + } +} + +pub struct ThreadPool { + workers: Vec, +} + +impl ThreadPool { + /// Create a new thread pool. + /// + /// # Panics + /// + /// - if 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(&self, f: F) + where F: FnOnce() + Send + 'static + { + thread::spawn(f); + } +} -- 2.39.5