I have the following contrived Rust code:
use std::thread;
const THREAD_COUNT: u8 = 10;
struct DropMe {
id: u8,
}
impl Drop for DropMe {
fn drop(&mut self) {
println!("Dropped item {}", self.id);
}
}
fn main() {
let outer_drop_me = DropMe { id: 255 };
println!(
"Created instance outside of threads with ID: {}",
&outer_drop_me.id
);
for i in 0..THREAD_COUNT {
let drop_me = DropMe { id: i };
thread::spawn(move || {
println!("Spawned thread {}", drop_me.id);
// Poor man's substitute for illustrating blocking I/O
thread::sleep(std::time::Duration::from_millis(500));
// Poor man's substitute for illustrating a cleanup function
drop(drop_me);
});
}
// outer_drop_me should be dropped automatically here as it goes out of
// scope
}
The output of which is as follows:
Created instance outside of threads with ID: 255
Spawned thread 0
Spawned thread 1
Spawned thread 2
Spawned thread 3
Spawned thread 4
Spawned thread 5
Spawned thread 6
Spawned thread 7
Spawned thread 8
Dropped item 255
Spawned thread 9
How can I do cleanup in threads where the code inside those threads may be blocking, but the process is being terminated (e.g. by way of SIGTERM
)?
In this contrived example, one could join
on the returned thread handles from the spawned threads, but what if join
is not available and the child threads are blocking? Do you just resign yourself to forfeiting the cleanup code after the part of the code that may be blocking?