tools: add AsyncMutex

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2019-04-29 14:16:15 +02:00
parent 3a9bea3918
commit d82ed9b0f5
2 changed files with 41 additions and 0 deletions

View File

@ -20,6 +20,7 @@ use std::collections::HashMap;
use serde_json::Value; use serde_json::Value;
pub mod async_mutex;
pub mod timer; pub mod timer;
pub mod wrapped_reader_stream; pub mod wrapped_reader_stream;
#[macro_use] #[macro_use]

40
src/tools/async_mutex.rs Normal file
View File

@ -0,0 +1,40 @@
use std::marker::PhantomData;
use futures::Poll;
use futures::future::Future;
use tokio::sync::lock::Lock as TokioLock;
pub use tokio::sync::lock::LockGuard as AsyncLockGuard;
pub struct AsyncMutex<T>(TokioLock<T>);
unsafe impl<T> Sync for AsyncMutex<T> {}
impl<T> AsyncMutex<T> {
pub fn new(value: T) -> Self {
Self(TokioLock::new(value))
}
// <E> to allow any error type (we never error, so we have no error type of our own)
pub fn lock<E>(&self) -> LockFuture<T, E> {
LockFuture {
lock: self.0.clone(),
_error: PhantomData,
}
}
}
/// Represents a lock to be held in the future:
pub struct LockFuture<T, E> {
lock: TokioLock<T>,
// We can't error and we don't want to enforce a specific error type either
_error: PhantomData<E>,
}
impl<T, E> Future for LockFuture<T, E> {
type Item = AsyncLockGuard<T>;
type Error = E;
fn poll(&mut self) -> Poll<AsyncLockGuard<T>, E> {
Ok(self.lock.poll_lock())
}
}