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

[semaphore] Add TryAcquireAll function #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
18 changes: 18 additions & 0 deletions semaphore/semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,24 @@ func (s *Weighted) TryAcquire(n int64) bool {
return success
}

// TryAcquireAll acquires all free weight from the semaphore without blocking.
// Returns the weight acquired. Returns 0 and leaves the semaphore unchanged if
// no weight was available.
func (s *Weighted) TryAcquireAll() int64 {
s.mu.Lock()
defer s.mu.Unlock()

// When somebody waits for a token there are obviously not enough tokens
// for waiters already waiting. Consequently, there are no free tokens.
if s.waiters.Len() > 0 {
return 0
}

free := s.size - s.cur
s.cur = s.size
return free
}

// Release releases the semaphore with a weight of n.
func (s *Weighted) Release(n int64) {
s.mu.Lock()
Expand Down