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

tokio-sync: add acquire_many and try_acquire_many methods to Sempahore #3067

Merged
merged 1 commit into from Nov 10, 2020
Merged
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
24 changes: 22 additions & 2 deletions tokio/src/sync/semaphore.rs
Expand Up @@ -27,7 +27,7 @@ pub struct Semaphore {
#[derive(Debug)]
pub struct SemaphorePermit<'a> {
sem: &'a Semaphore,
permits: u16,
permits: u32,
}

/// An owned permit from the semaphore.
Expand All @@ -39,7 +39,7 @@ pub struct SemaphorePermit<'a> {
#[derive(Debug)]
pub struct OwnedSemaphorePermit {
sem: Arc<Semaphore>,
permits: u16,
permits: u32,
}

/// Error returned from the [`Semaphore::try_acquire`] function.
Expand Down Expand Up @@ -104,6 +104,15 @@ impl Semaphore {
}
}

/// Acquires `n` permits from the semaphore
pub async fn acquire_many(&self, n: u32) -> SemaphorePermit<'_> {
self.ll_sem.acquire(n).await.unwrap();
SemaphorePermit {
sem: &self,
permits: n,
}
}

/// Tries to acquire a permit from the semaphore.
pub fn try_acquire(&self) -> Result<SemaphorePermit<'_>, TryAcquireError> {
match self.ll_sem.try_acquire(1) {
Expand All @@ -115,6 +124,17 @@ impl Semaphore {
}
}

/// Tries to acquire `n` permits from the semaphore.
pub fn try_acquire_many(&self, n: u32) -> Result<SemaphorePermit<'_>, TryAcquireError> {
match self.ll_sem.try_acquire(n) {
Ok(_) => Ok(SemaphorePermit {
sem: self,
permits: n,
}),
Err(_) => Err(TryAcquireError(())),
}
}

/// Acquires permit from the semaphore.
///
/// The semaphore must be wrapped in an [`Arc`] to call this method.
Expand Down