use async_lock::Mutex;
use std::future::Future;
#[derive(Debug)]
pub struct AQueue {
lock: Mutex<()>,
}
impl Default for AQueue {
#[inline]
fn default() -> Self {
AQueue { lock: Mutex::new(()) }
}
}
impl AQueue {
#[inline]
pub fn new() -> AQueue {
AQueue::default()
}
#[inline]
pub fn sync_run<A, R>(&self, call: impl FnOnce(A) -> R, arg: A) -> R {
loop {
let guard = self.lock.try_lock();
if guard.is_some() {
return call(arg);
} else {
std::thread::yield_now()
}
}
}
#[inline]
pub async fn run<'a, A, T, R>(&self, call: impl FnOnce(&'a A) -> T, arg: &'a A) -> R
where
T: Future<Output = R>,
{
let _guard = self.lock.lock().await;
call(arg).await
}
}