Skip to content

Section 21.3: Text recommends self.workers.drain(..) in Drop for ThreadPool, but final lib.rs uses worker.thread.take() #393

@marhla8

Description

@marhla8

Description

While studying Section 21.3 – Graceful Shutdown and Cleanup, I noticed a potential inconsistency between the explanation in the text and the final version of lib.rs provided at the end of the section.

Details

In the text, after encountering the ownership issue with JoinHandle, the book suggests that using Vec::drain(..) is a better alternative than wrapping thread in an Option. The explanation explicitly states that using Option<JoinHandle<()>> is more of a workaround and that drain(..) leads to cleaner and more idiomatic code.

Example from the text:

for worker in self.workers.drain(..) {
println!("Shutting down worker {}", worker.id);
worker.thread.join().unwrap();
}

However, the final lib.rs provided at the end of the section uses a different approach:

for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);

if let Some(thread) = worker.thread.take() {
    thread.join().unwrap();
}

}

Question

Is this change intentional?

If so, it might be helpful to include a brief explanation of why the final version switches back to using Option instead of the previously recommended drain(..) approach.
If not, perhaps the final lib.rs could be updated to match the earlier explanation for consistency.

Suggestion

To improve clarity for readers, it might help to either:

  • Keep the final implementation consistent with the drain(..) approach, or
  • Add a note explaining the trade-offs and why the final version uses Option.

Thanks for the great material—this section was very insightful, especially regarding ownership and graceful shutdown patterns.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions