Skip to content

Commit

Permalink
Merge pull request #20 from espindola/future
Browse files Browse the repository at this point in the history
Simplify using lock_arc
  • Loading branch information
taiki-e committed Jan 28, 2022
2 parents 2710371 + 9a92efd commit 1b63cc6
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 1b63cc6

Please sign in to comment.