1use std::mem::transmute;
2use std::thread;
3use std::thread::JoinHandle;
4
5pub struct ScopedThread {
6 handle: Option<JoinHandle<()>>
7}
8
9impl ScopedThread {
10 pub fn spawn<'scope, F>(f: F) -> ScopedThread
11 where
12 F: FnOnce() + Send + 'scope {
13 let f: Box<dyn FnOnce() + Send + 'scope> = Box::new(f);
15 let f: Box<dyn FnOnce() + Send + 'static> = unsafe { transmute(f) };
16
17 let handle = thread::spawn(f);
18 ScopedThread {
19 handle: Some(handle)
20 }
21 }
22}
23
24impl Drop for ScopedThread {
25 fn drop(&mut self) {
26 if let Some(handle) = self.handle.take() {
27 handle.join().unwrap();
28 }
29 }
30}