Next, then, we’ll implement the Drop trait to call join on each of the threads in the pool so they can finish the requests they’re working on before closing. Then we’ll implement a way to tell the threads they should stop accepting new requests and shut down. To see this code in action, we’ll modify our server to accept only two requests before gracefully shutting down its thread pool.

    Let’s start with implementing Drop on our thread pool. When the pool is dropped, our threads should all join to make sure they finish their work. Listing 20-22 shows a first attempt at a Drop implementation; this code won’t quite work yet.

    Filename: src/lib.rs

    Listing 20-22: Joining each thread when the thread pool goes out of scope

    First, we loop through each of the thread pool workers. We use &mut for this because self is a mutable reference, and we also need to be able to mutate worker. For each worker, we print a message saying that this particular worker is shutting down, and then we call join on that worker’s thread. If the call to join fails, we use unwrap to make Rust panic and go into an ungraceful shutdown.

    Here is the error we get when we compile this code:

    1. $ cargo check
    2. Checking hello v0.1.0 (file:///projects/hello)
    3. error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
    4. --> src/lib.rs:52:13
    5. |
    6. 52 | worker.thread.join().unwrap();
    7. | ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call
    8. | |
    9. | move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait
    10. |
    11. note: this function takes ownership of the receiver `self`, which moves `worker.thread`
    12. For more information about this error, try `rustc --explain E0507`.
    13. error: could not compile `hello` due to previous error

    The error tells us we can’t call join because we only have a mutable borrow of each worker and join takes ownership of its argument. To solve this issue, we need to move the thread out of the Worker instance that owns thread so join can consume the thread. We did this in Listing 17-15: if Worker holds an Option> instead, we can call the take method on the Option to move the value out of the Some variant and leave a None variant in its place. In other words, a Worker that is running will have a Some variant in thread, and when we want to clean up a Worker, we’ll replace Some with None so the Worker doesn’t have a thread to run.

    So we know we want to update the definition of Worker like this:

    Filename: src/lib.rs

    1. use std::{
    2. sync::{mpsc, Arc, Mutex},
    3. thread,
    4. };
    5. pub struct ThreadPool {
    6. workers: Vec<Worker>,
    7. sender: mpsc::Sender<Job>,
    8. }
    9. type Job = Box<dyn FnOnce() + Send + 'static>;
    10. impl ThreadPool {
    11. /// Create a new ThreadPool.
    12. ///
    13. /// The size is the number of threads in the pool.
    14. ///
    15. /// # Panics
    16. ///
    17. /// The `new` function will panic if the size is zero.
    18. pub fn new(size: usize) -> ThreadPool {
    19. assert!(size > 0);
    20. let (sender, receiver) = mpsc::channel();
    21. let receiver = Arc::new(Mutex::new(receiver));
    22. let mut workers = Vec::with_capacity(size);
    23. for id in 0..size {
    24. workers.push(Worker::new(id, Arc::clone(&receiver)));
    25. }
    26. ThreadPool { workers, sender }
    27. }
    28. pub fn execute<F>(&self, f: F)
    29. where
    30. F: FnOnce() + Send + 'static,
    31. {
    32. let job = Box::new(f);
    33. self.sender.send(job).unwrap();
    34. }
    35. }
    36. impl Drop for ThreadPool {
    37. fn drop(&mut self) {
    38. for worker in &mut self.workers {
    39. println!("Shutting down worker {}", worker.id);
    40. worker.thread.join().unwrap();
    41. }
    42. }
    43. }
    44. struct Worker {
    45. id: usize,
    46. thread: Option<thread::JoinHandle<()>>,
    47. }
    48. impl Worker {
    49. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
    50. let thread = thread::spawn(move || loop {
    51. let job = receiver.lock().unwrap().recv().unwrap();
    52. println!("Worker {id} got a job; executing.");
    53. job();
    54. });
    55. Worker { id, thread }
    56. }
    57. }

    Now let’s lean on the compiler to find the other places that need to change. Checking this code, we get two errors:

    1. $ cargo check
    2. Checking hello v0.1.0 (file:///projects/hello)
    3. error[E0599]: no method named `join` found for enum `Option` in the current scope
    4. --> src/lib.rs:52:27
    5. |
    6. 52 | worker.thread.join().unwrap();
    7. | ^^^^ method not found in `Option<JoinHandle<()>>`
    8. error[E0308]: mismatched types
    9. --> src/lib.rs:72:22
    10. |
    11. 72 | Worker { id, thread }
    12. | ^^^^^^ expected enum `Option`, found struct `JoinHandle`
    13. |
    14. = note: expected enum `Option<JoinHandle<()>>`
    15. found struct `JoinHandle<_>`
    16. help: try wrapping the expression in `Some`
    17. |
    18. 72 | Worker { id, thread: Some(thread) }
    19. | +++++++++++++ +
    20. Some errors have detailed explanations: E0308, E0599.
    21. For more information about an error, try `rustc --explain E0308`.
    22. error: could not compile `hello` due to 2 previous errors

    Let’s address the second error, which points to the code at the end of Worker::new; we need to wrap the thread value in Some when we create a new Worker. Make the following changes to fix this error:

    The first error is in our Drop implementation. We mentioned earlier that we intended to call take on the Option value to move thread out of worker. The following changes will do so:

    Filename: src/lib.rs

    1. use std::{
    2. sync::{mpsc, Arc, Mutex},
    3. thread,
    4. };
    5. pub struct ThreadPool {
    6. workers: Vec<Worker>,
    7. sender: mpsc::Sender<Job>,
    8. }
    9. type Job = Box<dyn FnOnce() + Send + 'static>;
    10. impl ThreadPool {
    11. /// Create a new ThreadPool.
    12. ///
    13. /// The size is the number of threads in the pool.
    14. ///
    15. /// # Panics
    16. ///
    17. /// The `new` function will panic if the size is zero.
    18. pub fn new(size: usize) -> ThreadPool {
    19. assert!(size > 0);
    20. let (sender, receiver) = mpsc::channel();
    21. let receiver = Arc::new(Mutex::new(receiver));
    22. let mut workers = Vec::with_capacity(size);
    23. for id in 0..size {
    24. workers.push(Worker::new(id, Arc::clone(&receiver)));
    25. }
    26. ThreadPool { workers, sender }
    27. }
    28. pub fn execute<F>(&self, f: F)
    29. where
    30. F: FnOnce() + Send + 'static,
    31. {
    32. let job = Box::new(f);
    33. self.sender.send(job).unwrap();
    34. }
    35. }
    36. impl Drop for ThreadPool {
    37. fn drop(&mut self) {
    38. println!("Shutting down worker {}", worker.id);
    39. if let Some(thread) = worker.thread.take() {
    40. thread.join().unwrap();
    41. }
    42. }
    43. }
    44. }
    45. struct Worker {
    46. id: usize,
    47. thread: Option<thread::JoinHandle<()>>,
    48. }
    49. impl Worker {
    50. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
    51. let thread = thread::spawn(move || loop {
    52. let job = receiver.lock().unwrap().recv().unwrap();
    53. println!("Worker {id} got a job; executing.");
    54. job();
    55. });
    56. Worker {
    57. id,
    58. thread: Some(thread),
    59. }
    60. }
    61. }

    As discussed in Chapter 17, the take method on Option takes the Some variant out and leaves None in its place. We’re using if let to destructure the Some and get the thread; then we call join on the thread. If a worker’s thread is already None, we know that worker has already had its thread cleaned up, so nothing happens in that case.

    With all the changes we’ve made, our code compiles without any warnings. However, the bad news is this code doesn’t function the way we want it to yet. The key is the logic in the closures run by the threads of the Worker instances: at the moment, we call join, but that won’t shut down the threads because they loop forever looking for jobs. If we try to drop our ThreadPool with our current implementation of drop, the main thread will block forever waiting for the first thread to finish.

    To fix this problem, we’ll need a change in the ThreadPool drop implementation and then a change in the Worker loop.

    First, we’ll change the ThreadPool drop implementation to explicitly drop the sender before waiting for the threads to finish. Listing 20-23 shows the changes to ThreadPool to explicitly drop sender. We use the same Option and take technique as we did with the thread to be able to move sender out of ThreadPool:

    Filename: src/lib.rs

    1. use std::{
    2. sync::{mpsc, Arc, Mutex},
    3. thread,
    4. };
    5. pub struct ThreadPool {
    6. workers: Vec<Worker>,
    7. sender: Option<mpsc::Sender<Job>>,
    8. }
    9. // --snip--
    10. type Job = Box<dyn FnOnce() + Send + 'static>;
    11. impl ThreadPool {
    12. /// Create a new ThreadPool.
    13. ///
    14. /// The size is the number of threads in the pool.
    15. ///
    16. /// # Panics
    17. ///
    18. /// The `new` function will panic if the size is zero.
    19. pub fn new(size: usize) -> ThreadPool {
    20. // --snip--
    21. assert!(size > 0);
    22. let (sender, receiver) = mpsc::channel();
    23. let receiver = Arc::new(Mutex::new(receiver));
    24. let mut workers = Vec::with_capacity(size);
    25. for id in 0..size {
    26. workers.push(Worker::new(id, Arc::clone(&receiver)));
    27. }
    28. ThreadPool {
    29. workers,
    30. sender: Some(sender),
    31. }
    32. }
    33. pub fn execute<F>(&self, f: F)
    34. where
    35. F: FnOnce() + Send + 'static,
    36. {
    37. let job = Box::new(f);
    38. self.sender.as_ref().unwrap().send(job).unwrap();
    39. }
    40. }
    41. impl Drop for ThreadPool {
    42. fn drop(&mut self) {
    43. drop(self.sender.take());
    44. for worker in &mut self.workers {
    45. println!("Shutting down worker {}", worker.id);
    46. if let Some(thread) = worker.thread.take() {
    47. thread.join().unwrap();
    48. }
    49. }
    50. }
    51. }
    52. struct Worker {
    53. id: usize,
    54. thread: Option<thread::JoinHandle<()>>,
    55. }
    56. impl Worker {
    57. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
    58. let thread = thread::spawn(move || loop {
    59. let job = receiver.lock().unwrap().recv().unwrap();
    60. println!("Worker {id} got a job; executing.");
    61. job();
    62. });
    63. Worker {
    64. id,
    65. thread: Some(thread),
    66. }
    67. }
    68. }

    Listing 20-23: Explicitly drop sender before joining the worker threads

    Dropping sender closes the channel, which indicates no more messages will be sent. When that happens, all the calls to recv that the workers do in the infinite loop will return an error. In Listing 20-24, we change the Worker loop to gracefully exit the loop in that case, which means the threads will finish when the ThreadPool drop implementation calls join on them.

    Filename: src/lib.rs

    1. use std::{
    2. sync::{mpsc, Arc, Mutex},
    3. thread,
    4. };
    5. pub struct ThreadPool {
    6. workers: Vec<Worker>,
    7. sender: Option<mpsc::Sender<Job>>,
    8. }
    9. type Job = Box<dyn FnOnce() + Send + 'static>;
    10. impl ThreadPool {
    11. /// Create a new ThreadPool.
    12. ///
    13. /// The size is the number of threads in the pool.
    14. ///
    15. /// # Panics
    16. ///
    17. /// The `new` function will panic if the size is zero.
    18. pub fn new(size: usize) -> ThreadPool {
    19. assert!(size > 0);
    20. let (sender, receiver) = mpsc::channel();
    21. let receiver = Arc::new(Mutex::new(receiver));
    22. let mut workers = Vec::with_capacity(size);
    23. for id in 0..size {
    24. workers.push(Worker::new(id, Arc::clone(&receiver)));
    25. }
    26. ThreadPool {
    27. workers,
    28. sender: Some(sender),
    29. }
    30. }
    31. pub fn execute<F>(&self, f: F)
    32. where
    33. F: FnOnce() + Send + 'static,
    34. {
    35. let job = Box::new(f);
    36. self.sender.as_ref().unwrap().send(job).unwrap();
    37. }
    38. }
    39. impl Drop for ThreadPool {
    40. fn drop(&mut self) {
    41. drop(self.sender.take());
    42. for worker in &mut self.workers {
    43. println!("Shutting down worker {}", worker.id);
    44. if let Some(thread) = worker.thread.take() {
    45. }
    46. }
    47. }
    48. }
    49. struct Worker {
    50. id: usize,
    51. thread: Option<thread::JoinHandle<()>>,
    52. }
    53. impl Worker {
    54. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
    55. let thread = thread::spawn(move || loop {
    56. match receiver.lock().unwrap().recv() {
    57. Ok(job) => {
    58. println!("Worker {id} got a job; executing.");
    59. job();
    60. }
    61. Err(_) => {
    62. println!("Worker {id} disconnected; shutting down.");
    63. break;
    64. }
    65. }
    66. });
    67. Worker {
    68. id,
    69. thread: Some(thread),
    70. }
    71. }
    72. }

    Listing 20-24: Explicitly break out of the loop when recv returns an error

    Filename: src/main.rs

    Listing 20-25: Shut down the server after serving two requests by exiting the loop

    You wouldn’t want a real-world web server to shut down after serving only two requests. This code just demonstrates that the graceful shutdown and cleanup is in working order.

    The take method is defined in the Iterator trait and limits the iteration to the first two items at most. The ThreadPool will go out of scope at the end of main, and the drop implementation will run.

    Start the server with cargo run, and make three requests. The third request should error, and in your terminal you should see output similar to this:

    1. $ cargo run
    2. Compiling hello v0.1.0 (file:///projects/hello)
    3. Finished dev [unoptimized + debuginfo] target(s) in 1.0s
    4. Running `target/debug/hello`
    5. Worker 0 got a job; executing.
    6. Shutting down.
    7. Shutting down worker 0
    8. Worker 3 got a job; executing.
    9. Worker 1 disconnected; shutting down.
    10. Worker 2 disconnected; shutting down.
    11. Worker 3 disconnected; shutting down.
    12. Worker 0 disconnected; shutting down.
    13. Shutting down worker 1
    14. Shutting down worker 2
    15. Shutting down worker 3

    You might see a different ordering of workers and messages printed. We can see how this code works from the messages: workers 0 and 3 got the first two requests. The server stopped accepting connections after the second connection, and the Drop implementation on ThreadPool starts executing before worker 3 even starts its job. Dropping the sender disconnects all the workers and tells them to shut down. The workers each print a message when they disconnect, and then the thread pool calls join to wait for each worker thread to finish.

    Notice one interesting aspect of this particular execution: the ThreadPool dropped the sender, and before any worker received an error, we tried to join worker 0. Worker 0 had not yet gotten an error from recv, so the main thread blocked waiting for worker 0 to finish. In the meantime, worker 3 received a job and then all threads received an error. When worker 0 finished, the main thread waited for the rest of the workers to finish. At that point, they had all exited their loops and stopped.

    Congrats! We’ve now completed our project; we have a basic web server that uses a thread pool to respond asynchronously. We’re able to perform a graceful shutdown of the server, which cleans up all the threads in the pool.

    Here’s the full code for reference:

    Filename: src/main.rs

    1. use hello::ThreadPool;
    2. use std::fs;
    3. use std::io::prelude::*;
    4. use std::net::TcpListener;
    5. use std::net::TcpStream;
    6. use std::thread;
    7. use std::time::Duration;
    8. fn main() {
    9. let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    10. let pool = ThreadPool::new(4);
    11. for stream in listener.incoming().take(2) {
    12. let stream = stream.unwrap();
    13. pool.execute(|| {
    14. handle_connection(stream);
    15. });
    16. }
    17. println!("Shutting down.");
    18. }
    19. fn handle_connection(mut stream: TcpStream) {
    20. let mut buffer = [0; 1024];
    21. stream.read(&mut buffer).unwrap();
    22. let get = b"GET / HTTP/1.1\r\n";
    23. let sleep = b"GET /sleep HTTP/1.1\r\n";
    24. let (status_line, filename) = if buffer.starts_with(get) {
    25. ("HTTP/1.1 200 OK", "hello.html")
    26. } else if buffer.starts_with(sleep) {
    27. thread::sleep(Duration::from_secs(5));
    28. ("HTTP/1.1 200 OK", "hello.html")
    29. } else {
    30. ("HTTP/1.1 404 NOT FOUND", "404.html")
    31. };
    32. let contents = fs::read_to_string(filename).unwrap();
    33. let response = format!(
    34. "{}\r\nContent-Length: {}\r\n\r\n{}",
    35. status_line,
    36. contents.len(),
    37. contents
    38. );
    39. stream.write_all(response.as_bytes()).unwrap();
    40. stream.flush().unwrap();
    41. }

    Filename: src/lib.rs

    1. use std::{
    2. sync::{mpsc, Arc, Mutex},
    3. thread,
    4. };
    5. pub struct ThreadPool {
    6. workers: Vec<Worker>,
    7. sender: Option<mpsc::Sender<Job>>,
    8. }
    9. type Job = Box<dyn FnOnce() + Send + 'static>;
    10. impl ThreadPool {
    11. /// Create a new ThreadPool.
    12. ///
    13. /// The size is the number of threads in the pool.
    14. ///
    15. /// # Panics
    16. ///
    17. /// The `new` function will panic if the size is zero.
    18. pub fn new(size: usize) -> ThreadPool {
    19. assert!(size > 0);
    20. let (sender, receiver) = mpsc::channel();
    21. let receiver = Arc::new(Mutex::new(receiver));
    22. let mut workers = Vec::with_capacity(size);
    23. for id in 0..size {
    24. workers.push(Worker::new(id, Arc::clone(&receiver)));
    25. }
    26. ThreadPool {
    27. workers,
    28. sender: Some(sender),
    29. }
    30. }
    31. pub fn execute<F>(&self, f: F)
    32. where
    33. F: FnOnce() + Send + 'static,
    34. {
    35. let job = Box::new(f);
    36. self.sender.as_ref().unwrap().send(job).unwrap();
    37. }
    38. }
    39. impl Drop for ThreadPool {
    40. fn drop(&mut self) {
    41. drop(self.sender.take());
    42. for worker in &mut self.workers {
    43. println!("Shutting down worker {}", worker.id);
    44. if let Some(thread) = worker.thread.take() {
    45. thread.join().unwrap();
    46. }
    47. }
    48. }
    49. }
    50. struct Worker {
    51. id: usize,
    52. thread: Option<thread::JoinHandle<()>>,
    53. }
    54. impl Worker {
    55. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
    56. let thread = thread::spawn(move || loop {
    57. let message = receiver.lock().unwrap().recv();
    58. match message {
    59. Ok(job) => {
    60. println!("Worker {id} got a job; executing.");
    61. job();
    62. }
    63. Err(_) => {
    64. println!("Worker {id} disconnected; shutting down.");
    65. break;
    66. }
    67. }
    68. });
    69. Worker {
    70. id,
    71. thread: Some(thread),
    72. }
    73. }
    74. }
    • Add more documentation to ThreadPool and its public methods.
    • Add tests of the library’s functionality.
    • Change calls to to more robust error handling.
    • Use ThreadPool to perform some task other than serving web requests.

    Well done! You’ve made it to the end of the book! We want to thank you for joining us on this tour of Rust. You’re now ready to implement your own Rust projects and help with other peoples’ projects. Keep in mind that there is a welcoming community of other Rustaceans who would love to help you with any challenges you encounter on your Rust journey.