use std::sync::{Arc, Mutex, PoisonError};
use std::thread::JoinHandle;
use super::Waker;
pub struct Job<T> {
out: Arc<Mutex<Option<T>>>,
thread: Option<JoinHandle<()>>,
}
impl<T> std::fmt::Debug for Job<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Job")
.field("finished", &self.is_finished())
.finish_non_exhaustive()
}
}
impl<T: Send + 'static> Job<T> {
pub fn spawn(work: impl FnOnce() -> T + Send + 'static) -> Self {
let out = Arc::new(Mutex::new(None));
let into = Arc::downgrade(&out);
let waker = Waker::new();
let thread = std::thread::spawn(move || {
struct Wake(Waker);
impl Drop for Wake {
fn drop(&mut self) {
self.0.wake();
}
}
let _wake = Wake(waker);
let done = work();
if let Some(into) = into.upgrade() {
*into.lock().unwrap_or_else(PoisonError::into_inner) = Some(done);
}
});
Job {
out,
thread: Some(thread),
}
}
}
impl<T> Job<T> {
pub fn poll(&mut self) -> Option<T> {
self.out.lock().unwrap_or_else(PoisonError::into_inner).take()
}
pub fn is_finished(&self) -> bool {
self.thread.as_ref().is_none_or(JoinHandle::is_finished)
}
pub fn wait(mut self) -> Option<T> {
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
self.poll()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn wakes() -> std::sync::MutexGuard<'static, ()> {
crate::app::tests::WAKES.lock().unwrap_or_else(PoisonError::into_inner)
}
#[test]
fn the_result_is_handed_over_once() {
let _wakes = wakes();
let mut job = Job::spawn(|| 6 * 7);
while !job.is_finished() {
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(job.poll(), Some(42));
assert_eq!(job.poll(), None);
assert!(format!("{job:?}").contains("finished: true"));
}
#[test]
fn waiting_gives_the_result_or_nothing_after_a_panic() {
let _wakes = wakes();
assert_eq!(Job::spawn(|| "done").wait(), Some("done"));
assert_eq!(Job::spawn(|| -> u8 { panic!("broke on purpose") }).wait(), None);
}
#[test]
fn nothing_turns_up_before_the_work_is_done() {
let _wakes = wakes();
let (tx, rx) = std::sync::mpsc::channel::<()>();
let mut job = Job::spawn(move || rx.recv().is_ok());
assert_eq!(job.poll(), None);
assert!(!job.is_finished());
tx.send(()).unwrap();
assert_eq!(job.wait(), Some(true));
}
}