Skip to content

Commit

Permalink
Simplify using lock_arc
Browse files Browse the repository at this point in the history
The future returned by lock_arc would already resolve to a
MutexGuardArc that kept the Arc<Mutex> alive. Unfortunately, sometimes
one needs to store the future itself, not the MutexGuardArc and the
future had a reference to the Arc<Mutex>.

With this patch, the future itself also has a Arc<Mutex>.
  • Loading branch information
espindola committed Jan 26, 2022
1 parent 2710371 commit 9a92efd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
17 changes: 11 additions & 6 deletions src/mutex.rs
@@ -1,5 +1,6 @@
use std::cell::UnsafeCell;
use std::fmt;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::process;
use std::sync::atomic::{AtomicUsize, Ordering};
Expand Down Expand Up @@ -263,6 +264,14 @@ impl<T: ?Sized> Mutex<T> {
}

impl<T: ?Sized> Mutex<T> {
async fn lock_arc_impl(self: Arc<Self>) -> MutexGuardArc<T> {
if let Some(guard) = self.try_lock_arc() {
return guard;
}
self.acquire_slow().await;
MutexGuardArc(self)
}

/// Acquires the mutex and clones a reference to it.
///
/// Returns an owned guard that releases the mutex when dropped.
Expand All @@ -280,12 +289,8 @@ impl<T: ?Sized> Mutex<T> {
/// # })
/// ```
#[inline]
pub async fn lock_arc(self: &Arc<Self>) -> MutexGuardArc<T> {
if let Some(guard) = self.try_lock_arc() {
return guard;
}
self.acquire_slow().await;
MutexGuardArc(self.clone())
pub fn lock_arc(self: &Arc<Self>) -> impl Future<Output = MutexGuardArc<T>> {
self.clone().lock_arc_impl()
}

/// Attempts to acquire the mutex and clone a reference to it.
Expand Down
10 changes: 9 additions & 1 deletion tests/mutex.rs
@@ -1,4 +1,3 @@
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::thread;
Expand Down Expand Up @@ -76,3 +75,12 @@ fn contention() {
assert_eq!(num_tasks, *lock);
});
}

#[test]
fn lifetime() {
// Show that the future keeps the mutex alive.
let _fut = {
let mutex = Arc::new(Mutex::new(0i32));
mutex.lock_arc()
};
}

0 comments on commit 9a92efd

Please sign in to comment.