use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
pub enum ThreadPool {
Custom(rayon::ThreadPool),
Global,
}
impl ThreadPool {
pub fn run<F: FnOnce() -> V + Send, V: Send>(&self, f: F) -> V {
match self {
ThreadPool::Custom(p) => p.install(f),
ThreadPool::Global => f(),
}
}
pub fn thread_count(&self) -> usize {
match self {
ThreadPool::Custom(p) => p.current_num_threads(),
ThreadPool::Global => rayon::current_num_threads(),
}
}
}
#[derive(Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
#[doc(hidden)]
pub fn into_raw(self) -> *const AtomicBool {
Arc::into_raw(self.0)
}
#[doc(hidden)]
pub unsafe fn from_raw(ptr: *const AtomicBool) -> Self {
let a = unsafe { Arc::from_raw(ptr) };
Self(a)
}
}