Skip to content

Commit d16bec7

Browse files
author
Jan Dubsky
committed
[semaphore] Add TryAcquireAll function
1 parent 8fcdb60 commit d16bec7

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

semaphore/semaphore.go

+18
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,24 @@ func (s *Weighted) TryAcquire(n int64) bool {
9494
return success
9595
}
9696

97+
// TryAcquireAll acquires all free weight from the semaphore without blocking.
98+
// Returns the weight acquired. Returns 0 and leaves the semaphore unchanged if
99+
// no weight was available.
100+
func (s *Weighted) TryAcquireAll() int64 {
101+
s.mu.Lock()
102+
defer s.mu.Unlock()
103+
104+
// When somebody waits for a token there are obviously not enough tokens
105+
// for waiters already waiting. Consequently, there are no free tokens.
106+
if s.waiters.Len() > 0 {
107+
return 0
108+
}
109+
110+
free := s.size - s.cur
111+
s.cur = s.size
112+
return free
113+
}
114+
97115
// Release releases the semaphore with a weight of n.
98116
func (s *Weighted) Release(n int64) {
99117
s.mu.Lock()

0 commit comments

Comments
 (0)