use std::mem::transmute;
use std::thread;
use std::thread::JoinHandle;
pub struct ScopedThread {
handle: Option<JoinHandle<()>>
}
impl ScopedThread {
pub fn spawn<'scope, F>(f: F) -> ScopedThread
where
F: FnOnce() + Send + 'scope {
let f: Box<dyn FnOnce() + Send + 'scope> = Box::new(f);
let f: Box<dyn FnOnce() + Send + 'static> = unsafe { transmute(f) };
let handle = thread::spawn(f);
ScopedThread {
handle: Some(handle)
}
}
}
impl Drop for ScopedThread {
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
handle.join().unwrap();
}
}
}