Skip to content

Commit

Permalink
sync: add getter for the mutex from a guard (#3928)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijackson committed Jul 20, 2021
1 parent 549e89e commit 2520048
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions tokio/src/sync/mutex.rs
Expand Up @@ -573,6 +573,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<T> {
this.lock
}
}

impl<T: ?Sized> Drop for MutexGuard<'_, T> {
Expand Down Expand Up @@ -608,6 +634,35 @@ impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {

// === impl OwnedMutexGuard ===

impl<T: ?Sized> OwnedMutexGuard<T> {
/// Returns a reference to the original `Arc<Mutex>`.
///
/// ```
/// use std::sync::Arc;
/// use tokio::sync::{Mutex, OwnedMutexGuard};
///
/// async fn unlock_and_relock(guard: OwnedMutexGuard<u32>) -> OwnedMutexGuard<u32> {
/// println!("1. contains: {:?}", *guard);
/// let mutex: Arc<Mutex<u32>> = 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<Mutex<T>> {
&this.lock
}
}

impl<T: ?Sized> Drop for OwnedMutexGuard<T> {
fn drop(&mut self) {
self.lock.s.release(1)
Expand Down

1 comment on commit 2520048

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark 'sync_mpsc'.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 2.

Benchmark suite Current: 2520048 Previous: 549e89e Ratio
send_large 65769 ns/iter (± 8506) 25393 ns/iter (± 3642) 2.59

This comment was automatically generated by workflow using github-action-benchmark.

CC: @tokio-rs/maintainers

Please sign in to comment.