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

Release 2.5.0 #21

Merged
merged 2 commits into from Feb 19, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,7 @@
# Version 2.5.0

- Fix an issue where the future returned by `Mutex::lock_arc`/`Semaphore::acquire_arc` holds a reference to `self`. (#20, #21)

# Version 2.4.0

- Add WASM support. (#14)
Expand Down
4 changes: 1 addition & 3 deletions Cargo.toml
Expand Up @@ -3,15 +3,13 @@ name = "async-lock"
# When publishing a new version:
# - Update CHANGELOG.md
# - Create "v2.x.y" git tag
version = "2.4.0"
version = "2.5.0"
authors = ["Stjepan Glavina <stjepang@gmail.com>"]
edition = "2018"
rust-version = "1.43"
description = "Async synchronization primitives"
license = "Apache-2.0 OR MIT"
repository = "https://github.com/smol-rs/async-lock"
homepage = "https://github.com/smol-rs/async-lock"
documentation = "https://docs.rs/async-lock"
keywords = ["lock", "mutex", "rwlock", "semaphore", "barrier"]
categories = ["asynchronous", "concurrency"]
exclude = ["/.*"]
Expand Down
31 changes: 18 additions & 13 deletions src/semaphore.rs
@@ -1,3 +1,4 @@
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

Expand Down Expand Up @@ -135,6 +136,21 @@ impl Semaphore {
}
}

async fn acquire_arc_impl(self: Arc<Self>) -> SemaphoreGuardArc {
let mut listener = None;

loop {
if let Some(guard) = self.try_acquire_arc() {
return guard;
}

match listener.take() {
None => listener = Some(self.event.listen()),
Some(l) => l.await,
}
}
}

/// Waits for an owned permit for a concurrent operation.
///
/// Returns a guard that releases the permit when dropped.
Expand All @@ -150,19 +166,8 @@ impl Semaphore {
/// let guard = s.acquire_arc().await;
/// # });
/// ```
pub async fn acquire_arc(self: &Arc<Self>) -> SemaphoreGuardArc {
let mut listener = None;

loop {
if let Some(guard) = self.try_acquire_arc() {
return guard;
}

match listener.take() {
None => listener = Some(self.event.listen()),
Some(l) => l.await,
}
}
pub fn acquire_arc(self: &Arc<Self>) -> impl Future<Output = SemaphoreGuardArc> {
self.clone().acquire_arc_impl()
}
}

Expand Down
9 changes: 9 additions & 0 deletions tests/semaphore.rs
Expand Up @@ -81,3 +81,12 @@ fn multi_resource() {
rx1.recv().unwrap();
});
}

#[test]
fn lifetime() {
// Show that the future keeps the semaphore alive.
let _fut = {
let mutex = Arc::new(Semaphore::new(2));
mutex.acquire_arc()
};
}