From 41e44c8df66acdd4d0237205192314ae42f0e5cc Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 5 Jul 2021 17:10:07 +0100 Subject: [PATCH 1/2] Provide MutexGuard::mutex() Signed-off-by: Ian Jackson --- tokio/src/sync/mutex.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 9fd7c912b6d..34eba1386d3 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -561,6 +561,32 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { marker: marker::PhantomData, }) } + + /// Returns a reference to the original `Mutex`. + /// + /// ``` + /// use tokio::sync::{Mutex, MutexGuard}; + /// + /// async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> { + /// println!("1. contains: {:?}", *guard); + /// let mutex = MutexGuard::mutex(&guard); + /// drop(guard); + /// let guard = mutex.lock().await; + /// println!("2. contains: {:?}", *guard); + /// guard + /// } + /// # + /// # #[tokio::main] + /// # async fn main() { + /// # let mutex = Mutex::new(0u32); + /// # let guard = mutex.lock().await; + /// # unlock_and_relock(guard).await; + /// # } + /// ``` + #[inline] + pub fn mutex(this: &Self) -> &'a Mutex { + this.lock + } } impl Drop for MutexGuard<'_, T> { From 5aa6958b38d4c88cf69cf942590ee885d5791596 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 5 Jul 2021 17:32:26 +0100 Subject: [PATCH 2/2] Provide OwnedMutexGuard::mutex() Signed-off-by: Ian Jackson --- tokio/src/sync/mutex.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 34eba1386d3..e5ccf7145e6 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -622,6 +622,35 @@ impl fmt::Display for MutexGuard<'_, T> { // === impl OwnedMutexGuard === +impl OwnedMutexGuard { + /// Returns a reference to the original `Arc`. + /// + /// ``` + /// use std::sync::Arc; + /// use tokio::sync::{Mutex, OwnedMutexGuard}; + /// + /// async fn unlock_and_relock(guard: OwnedMutexGuard) -> OwnedMutexGuard { + /// println!("1. contains: {:?}", *guard); + /// let mutex: Arc> = OwnedMutexGuard::mutex(&guard).clone(); + /// drop(guard); + /// let guard = mutex.lock_owned().await; + /// println!("2. contains: {:?}", *guard); + /// guard + /// } + /// # + /// # #[tokio::main] + /// # async fn main() { + /// # let mutex = Arc::new(Mutex::new(0u32)); + /// # let guard = mutex.lock_owned().await; + /// # unlock_and_relock(guard).await; + /// # } + /// ``` + #[inline] + pub fn mutex(this: &Self) -> &Arc> { + &this.lock + } +} + impl Drop for OwnedMutexGuard { fn drop(&mut self) { self.lock.s.release(1)