#![cfg(all(feature = "threads", not(target_family = "wasm")))]
use super::*;
impl<O: Send + 'static> JobQueue<O> {
#[cfg(all(feature = "threads", not(target_family = "wasm")))]
pub(super) fn prune_workers(&mut self) {
self.workers.retain(|worker| !worker.is_finished());
}
#[cfg(all(feature = "threads", not(target_family = "wasm")))]
pub(super) fn spawn_worker(
&mut self,
id: JobId,
job: Arc<dyn Job<Output = O>>,
context: JobContext,
status: Arc<AtomicU8>,
) {
let results = Arc::clone(&self.results);
self.workers.push(std::thread::spawn(move || {
status.store(JobStatus::Running.code(), Ordering::SeqCst);
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run(&context)))
.unwrap_or_else(|payload| Err(JobError::Panicked(panic_message(&payload))));
let final_status = match &outcome {
Ok(_) => JobStatus::Finished,
Err(JobError::Cancelled) => JobStatus::Cancelled,
Err(_) => JobStatus::Failed,
};
status.store(final_status.code(), Ordering::SeqCst);
if let Ok(mut results) = results.lock() {
results.push_back((id, outcome));
}
}));
}
#[cfg(all(feature = "threads", not(target_family = "wasm")))]
pub(super) fn schedule_pending(&mut self) {
self.prune_workers();
while self.workers.len() < MAX_WORKERS {
let Some((id, job, context, status)) = self.pending.pop() else {
break;
};
self.spawn_worker(id, job, context, Arc::clone(&status));
}
}
}