book icon indicating copy to clipboard operation
book copied to clipboard

Use idiomatic way to drop threads from the vector

Open andrei-21 opened this issue 2 years ago • 1 comments

  • [X] I have checked the latest main branch to see if this has already been fixed
  • [X] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch20-03-graceful-shutdown-and-cleanup.html#implementing-the-drop-trait-on-threadpool

Description of the problem: The suggested solution to move the thread out of the Worker instance is to wrap the thread into Option, however it is artificial, since Worker struct does not make sense with thread having None value.

Suggested fix: There is Vec::drain method which allows to move elements out of the vector. Then the code for drop will be:

impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in self.workers.drain(..) {
            println!("Shutting down worker {}", worker.id);

            worker.thread.join().unwrap();
        }
    }
}

andrei-21 avatar Jun 29 '22 23:06 andrei-21

PR for the suggested change #3249.

andrei-21 avatar Jun 29 '22 23:06 andrei-21