diff --git a/src/main.rs b/src/main.rs index 9a4e4ec..ec3fd74 100644 --- a/src/main.rs +++ b/src/main.rs @@ -44,6 +44,14 @@ impl ThreadPool { } Self { workers, sender } } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + self.sender.send(job).unwrap(); + } } type Job = Box; @@ -54,9 +62,7 @@ fn main() -> std::io::Result<()> { let pool = ThreadPool::new(4); for stream in listener.incoming() { let stream = stream?; - thread::spawn(|| { - handle_connection(stream).unwrap(); - }); + pool.execute(|| handle_connection(stream).unwrap()); } Ok(()) }