tools: add AsyncMutex::new_locked

Allows creating a pre-locked mutex, returning the mutex and
a guard.

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2019-05-29 10:27:24 +02:00
parent e6389f4e75
commit 0d32d71fb7

View File

@ -1,6 +1,7 @@
use std::marker::PhantomData;
use futures::Poll;
use failure::{bail, Error};
use futures::{Async, Poll};
use futures::future::Future;
use tokio::sync::lock::Lock as TokioLock;
pub use tokio::sync::lock::LockGuard as AsyncLockGuard;
@ -21,6 +22,15 @@ impl<T> AsyncMutex<T> {
_error: PhantomData,
}
}
pub fn new_locked(value: T) -> Result<(Self, AsyncLockGuard<T>), Error> {
let mut this = Self::new(value);
let guard = match this.0.poll_lock() {
Async::Ready(guard) => guard,
_ => bail!("failed to create locked mutex"),
};
Ok((this, guard))
}
}
/// Represents a lock to be held in the future: