The Rust Programming Language— 20.3 Graceful Shutdown and Cleanup

Luke
2 min readOct 16, 2022

--

This is a study note for https://doc.rust-lang.org/book/ch20-03-graceful-shutdown-and-cleanup.html

joining a thread handle would block the current thread to allow the thread being handled to finish. In this chapter, this is being used so that the main thread would wait for other threads to finish when before dropping ThreadPool.

struct variable cannot be moved out but we can use take to set it to default value. take is a std::mem function which is implemented for all types. Similarly, there are swap and replace. All these functions can be used to handle the cases where you want to move/modify a field in a struct. Notice that the type of the field has to allow take to happen. For example, field.take() when field is of type thread::JoinHandle<()> would require using Option<thread::JoinHandle<()>>.

&mut on a mutable variable is not necessary but Rust requires it for explicit.

Drop::drop is executed before the destruction of the variable happens.

A type cannot implement both drop and copy. Why? drop is for resource management purpose. copy means the variable can be copied by bytes copy which normally means there is no resource attached to the variable. So there should be few cases where a type has attached resource and also implements copy. Even if that happens, drop cannot reasonably written because multiple variables may control the same resource through copy.

The fields of a struct share its mutability, so self.sender here is &mut. The &mut is for worker — self.workers is mutable even without it.

--

--