1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//! A simple thread pool implementation.

use std::sync::{mpsc, Arc, Mutex};
use std::thread::{self, JoinHandle};

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

pub struct ThreadPool {
    sender: mpsc::Sender<ThreadPoolMessage>,
    workers: Vec<Worker>,
    joined: bool,
}

impl ThreadPool {
    /// Creates a new thread pool.
    /// If `size` is not greater than zero, the function **panics**.
    pub fn new(size: usize) -> Self {
        assert!(size > 0);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));
        let mut workers = Vec::new();
        for _ in 0..size {
            workers.push(Worker::new(Arc::clone(&receiver)));
        }

        Self {
            sender,
            workers,
            joined: false,
        }
    }

    /// Adds a job to the thread pool to be executed by a worker.
    pub fn queue<F>(&self, job: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.sender
            .send(ThreadPoolMessage::NewJob(Box::new(job)))
            .unwrap();
    }

    /// Blocks the current thread until all worker threads finish.
    pub fn join(&mut self) {
        for _ in &self.workers {
            self.sender.send(ThreadPoolMessage::Terminate).unwrap();
        }
        for worker in &mut self.workers {
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
        self.joined = true;
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        if !self.joined {
            self.join();
        }
    }
}

enum ThreadPoolMessage {
    NewJob(Job),
    Terminate,
}

struct Worker {
    thread: Option<JoinHandle<()>>,
}

impl Worker {
    /// Creates a worker that constantly listens for jobs in the thread
    /// pool and executes them.
    fn new(receiver: Arc<Mutex<mpsc::Receiver<ThreadPoolMessage>>>) -> Self {
        use ThreadPoolMessage::*;
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv().unwrap();
            match message {
                NewJob(job) => job(),
                Terminate => break,
            }
        });
        Self {
            thread: Some(thread),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    use std::io::prelude::*;
    use std::net::{TcpListener, TcpStream};
    use std::thread;
    use std::time::Duration;

    #[test]
    fn it_works() {
        let mut pool = ThreadPool::new(2);
        let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
        for stream in listener.incoming() {
            let stream = stream.unwrap();
            pool.queue(|| handle_stream(stream));
        }
        pool.join();

        fn handle_stream(mut stream: TcpStream) {
            let mut buf = [0; 1024];
            stream.read(&mut buf).unwrap();
            if buf.starts_with(b"GET /sleep HTTP/1.1\r\n") {
                println!("sleeping");
                thread::sleep(Duration::from_secs(5));
            }
            let message = "Hello world!";
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                message.len(),
                message
            );
            stream.write(response.as_bytes()).unwrap();
            stream.flush().unwrap();
        }
    }
}