#[cfg(not(target_arch = "wasm32"))]
use std::{sync::mpsc, thread};
#[cfg(not(target_arch = "wasm32"))]
use parking_lot::Mutex;
#[cfg(not(target_arch = "wasm32"))]
type Job = Box<dyn FnOnce() + Send + 'static>;
#[cfg(not(target_arch = "wasm32"))]
pub(super) struct Workers {
sender: Mutex<mpsc::Sender<Job>>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Workers {
pub(super) fn new(count: usize) -> Self {
let (sender, receiver) = mpsc::channel::<Job>();
let receiver = std::sync::Arc::new(Mutex::new(receiver));
for index in 0..count.max(1) {
let receiver = std::sync::Arc::clone(&receiver);
let spawned = thread::Builder::new()
.name(format!("lurq-image-decode-{index}"))
.spawn(move || {
loop {
let job = receiver.lock().recv();
match job {
Ok(job) => {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() {
tracing::error!(target: "lurq::images", "an image decode job panicked; the worker goes on");
}
}
Err(_) => break,
}
}
});
if let Err(error) = spawned {
tracing::error!(target: "lurq::images", "image decode thread {index} did not start: {error}");
}
}
Self {
sender: Mutex::new(sender),
}
}
pub(super) fn submit(&self, job: impl FnOnce() + Send + 'static) -> bool {
self.sender.lock().send(Box::new(job)).is_ok()
}
#[cfg(test)]
pub(super) fn closed() -> Self {
let (sender, _) = mpsc::channel::<Job>();
Self {
sender: Mutex::new(sender),
}
}
}
#[cfg(target_arch = "wasm32")]
pub(super) struct Workers;
#[cfg(target_arch = "wasm32")]
impl Workers {
pub(super) fn new(_count: usize) -> Self {
Self
}
pub(super) fn submit(&self, job: impl FnOnce() + Send + 'static) -> bool {
wasm_bindgen_futures::spawn_local(async move { job() });
true
}
}