Commit 583e12fa authored by Chris's avatar Chris
Browse files

[multi-threaded-web-server] async implementation MVP complete

parent bdba2b56
Loading
Loading
Loading
Loading
+57 −1
Original line number Diff line number Diff line
use std::{
    sync::{
        Arc,
        Mutex,
        mpsc
    },
    thread
};

pub struct ThreadPool;
pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static,>;

impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver))); }
        
        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap_or_default();
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}
impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        // let thread = thread::spawn(|| {}); // note: in production, use std::thread::Builder instead of this (in case you can't spawn new threads)
        let thread = thread::spawn(move || {
            loop {
                let job = receiver.lock().unwrap().recv().unwrap();
                println!("Worker {id} got a job; executing...");
                job();
            }
        });
        Worker {id, thread}
    }
}
 No newline at end of file
+4 −2
Original line number Diff line number Diff line
@@ -6,9 +6,11 @@ use std::{
    time::Duration,
};
use std::process::exit;
use multi_threaded_web_server::ThreadPool;

fn main() {
    println!("[multi-threaded-web-service] application started");
    let pool = ThreadPool::new(4);

    let listener = TcpListener::bind("127.0.0.1:7878").unwrap_or_else(|error| {
        eprintln!("error when binding to port 7878: {}", error);
@@ -23,9 +25,9 @@ fn main() {

        println!("[multi-threaded-web-service] connection established");

        thread::spawn(|| {
        pool.execute(|| {
            handle_connection(stream);
        });
        })
    }
}