diff options
author | Michael P. Jung <michael.jung@terreon.de> | 2019-12-10 17:01:23 +0100 |
---|---|---|
committer | Carl Lerche <me@carllerche.com> | 2019-12-10 08:01:23 -0800 |
commit | 975576952f33c64e4faaa616f67ae9d6b596e4aa (patch) | |
tree | 879c74c5fcf04e17fffe0b33b9b98a15bf1d464a /tokio/src/sync/mutex.rs | |
parent | 5d5755dca4586f80d591e5d61de3f245bf8c4506 (diff) |
Add Mutex::try_lock and (Unbounded)Receiver::try_recv (#1939)
Diffstat (limited to 'tokio/src/sync/mutex.rs')
-rw-r--r-- | tokio/src/sync/mutex.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 07a5a63f..35e13300 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -38,6 +38,7 @@ use crate::future::poll_fn; use crate::sync::semaphore; use std::cell::UnsafeCell; +use std::error::Error; use std::fmt; use std::ops::{Deref, DerefMut}; @@ -73,6 +74,30 @@ unsafe impl<T> Send for Mutex<T> where T: Send {} unsafe impl<T> Sync for Mutex<T> where T: Send {} unsafe impl<'a, T> Sync for MutexGuard<'a, T> where T: Send + Sync {} +/// An enumeration of possible errors associated with a `TryLockResult` +/// which can occur while trying to aquire a lock from the `try_lock` +/// method on a `Mutex`. +#[derive(Debug)] +pub enum TryLockError { + /// The lock could not be acquired at this time because the operation + /// would otherwise block. + WouldBlock, +} + +impl fmt::Display for TryLockError { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + fmt, + "{}", + match self { + TryLockError::WouldBlock => "operation would block" + } + ) + } +} + +impl Error for TryLockError {} + #[test] #[cfg(not(loom))] fn bounds() { @@ -104,6 +129,15 @@ impl<T> Mutex<T> { }); guard } + + /// Try to aquire the lock + pub fn try_lock(&self) -> Result<MutexGuard<'_, T>, TryLockError> { + let mut permit = semaphore::Permit::new(); + match permit.try_acquire(&self.s) { + Ok(_) => Ok(MutexGuard { lock: self, permit }), + Err(_) => Err(TryLockError::WouldBlock), + } + } } impl<'a, T> Drop for MutexGuard<'a, T> { |