Skip to content

Commit

Permalink
add decrease_permit
Browse files Browse the repository at this point in the history
  • Loading branch information
mox692 committed Feb 5, 2024
1 parent 131e7b4 commit 133cb02
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
21 changes: 21 additions & 0 deletions tokio/src/sync/batch_semaphore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,27 @@ impl Semaphore {
assert_eq!(rem, 0);
}

/// try to decrease at most `n` permits of this semaphore.
/// If the number of "permits" is negative, returns the number of "permits" that were reduced.
/// TODO: Doesn't that conflict with other places looking at self.permits?
pub(crate) fn decrease_permit(&self, n: usize) -> usize {
let mut curr_bit;
loop {
curr_bit = self.permits.load(Acquire);
let curr = curr_bit >> Self::PERMIT_SHIFT;
let new = curr.saturating_sub(n);
match self.permits.compare_exchange(
curr_bit,
new << Self::PERMIT_SHIFT,
AcqRel,
Acquire,
) {
Ok(_) => break,
Err(_) => continue,
};
}
std::cmp::min(curr_bit >> Self::PERMIT_SHIFT, n)
}
fn poll_acquire(
&self,
cx: &mut Context<'_>,
Expand Down
5 changes: 5 additions & 0 deletions tokio/src/sync/semaphore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,11 @@ impl Semaphore {
self.ll_sem.release(n);
}

/// docs
pub fn decrease_permit(&self, n: usize) -> usize {
self.ll_sem.decrease_permit(n)
}

/// Acquires a permit from the semaphore.
///
/// If the semaphore has been closed, this returns an [`AcquireError`].
Expand Down

0 comments on commit 133cb02

Please sign in to comment.