Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify using lock_arc #20

Merged
merged 1 commit into from
Jan 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/mutex.rs
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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()
};
}