Skip to content

Commit 1b63cc6

Browse files
authored
Merge pull request #20 from espindola/future
Simplify using lock_arc
2 parents 2710371 + 9a92efd commit 1b63cc6

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/mutex.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::cell::UnsafeCell;
22
use std::fmt;
3+
use std::future::Future;
34
use std::ops::{Deref, DerefMut};
45
use std::process;
56
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -263,6 +264,14 @@ impl<T: ?Sized> Mutex<T> {
263264
}
264265

265266
impl<T: ?Sized> Mutex<T> {
267+
async fn lock_arc_impl(self: Arc<Self>) -> MutexGuardArc<T> {
268+
if let Some(guard) = self.try_lock_arc() {
269+
return guard;
270+
}
271+
self.acquire_slow().await;
272+
MutexGuardArc(self)
273+
}
274+
266275
/// Acquires the mutex and clones a reference to it.
267276
///
268277
/// Returns an owned guard that releases the mutex when dropped.
@@ -280,12 +289,8 @@ impl<T: ?Sized> Mutex<T> {
280289
/// # })
281290
/// ```
282291
#[inline]
283-
pub async fn lock_arc(self: &Arc<Self>) -> MutexGuardArc<T> {
284-
if let Some(guard) = self.try_lock_arc() {
285-
return guard;
286-
}
287-
self.acquire_slow().await;
288-
MutexGuardArc(self.clone())
292+
pub fn lock_arc(self: &Arc<Self>) -> impl Future<Output = MutexGuardArc<T>> {
293+
self.clone().lock_arc_impl()
289294
}
290295

291296
/// Attempts to acquire the mutex and clone a reference to it.

tests/mutex.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
#[cfg(not(target_arch = "wasm32"))]
21
use std::sync::Arc;
32
#[cfg(not(target_arch = "wasm32"))]
43
use std::thread;
@@ -76,3 +75,12 @@ fn contention() {
7675
assert_eq!(num_tasks, *lock);
7776
});
7877
}
78+
79+
#[test]
80+
fn lifetime() {
81+
// Show that the future keeps the mutex alive.
82+
let _fut = {
83+
let mutex = Arc::new(Mutex::new(0i32));
84+
mutex.lock_arc()
85+
};
86+
}

0 commit comments

Comments
 (0)