sync: add acquire_many and try_acquire_many to Sempahore (#3067)

Fixes: #1550
This commit is contained in:
Darius Carrier 2020-11-10 09:39:30 -08:00 committed by GitHub
parent f1f8c3cde6
commit a52f5071bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -27,7 +27,7 @@ pub struct Semaphore {
#[derive(Debug)] #[derive(Debug)]
pub struct SemaphorePermit<'a> { pub struct SemaphorePermit<'a> {
sem: &'a Semaphore, sem: &'a Semaphore,
permits: u16, permits: u32,
} }
/// An owned permit from the semaphore. /// An owned permit from the semaphore.
@ -39,7 +39,7 @@ pub struct SemaphorePermit<'a> {
#[derive(Debug)] #[derive(Debug)]
pub struct OwnedSemaphorePermit { pub struct OwnedSemaphorePermit {
sem: Arc<Semaphore>, sem: Arc<Semaphore>,
permits: u16, permits: u32,
} }
/// Error returned from the [`Semaphore::try_acquire`] function. /// Error returned from the [`Semaphore::try_acquire`] function.
@ -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. /// Tries to acquire a permit from the semaphore.
pub fn try_acquire(&self) -> Result<SemaphorePermit<'_>, TryAcquireError> { pub fn try_acquire(&self) -> Result<SemaphorePermit<'_>, TryAcquireError> {
match self.ll_sem.try_acquire(1) { match self.ll_sem.try_acquire(1) {
@ -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. /// Acquires permit from the semaphore.
/// ///
/// The semaphore must be wrapped in an [`Arc`] to call this method. /// The semaphore must be wrapped in an [`Arc`] to call this method.