use std::thread::{self, JoinHandle};
#[must_use = "a Job runs in the background; join it to observe its result / propagate panics"]
pub struct Job<T: Send + 'static> {
handle: JoinHandle<T>,
}
impl<T: Send + 'static> Job<T> {
#[inline]
pub fn spawn<F>(f: F) -> Self
where
F: FnOnce() -> T + Send + 'static,
{
Job { handle: thread::spawn(f) }
}
#[inline]
pub fn join(self) -> thread::Result<T> {
self.handle.join()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runs_and_returns_value() {
let job = Job::spawn(|| 2 + 2);
assert_eq!(job.join().unwrap(), 4);
}
#[test]
fn overlaps_caller_work() {
let job = Job::spawn(|| (0u64..1_000).sum::<u64>());
let mut local = 0u64;
for i in 0..1_000 {
local += i;
}
assert_eq!(job.join().unwrap(), local);
}
#[test]
fn panic_becomes_err_not_abort() {
let job = Job::spawn(|| panic!("boom"));
assert!(job.join().is_err());
}
}