book
book copied to clipboard
Use idiomatic way to drop threads from the vector
- [X] I have checked the latest
mainbranch 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();
}
}
}
PR for the suggested change #3249.