[semaphore] Add TryAcquireAll function #19
+18
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
I use semaphore to guard a pool of objects. It other words tokens in the semaphore correspond to my items in the pool. The standard acquire function looks like this:
At the same time, I'd love to have a function
AcquireAll
that acquires all available resources in my pool at once. The problem is that because the current number of available resources is represented by the semaphore state (i.e. free semaphore tokens), I don't know how many tokens should I try to acquire from the semaphore.I for sure can do
semaphore.TryAcquire(1)
in a loop as long as it succeeds, but this would require linear time. Another solution is to callsemaphore.TryAcquire(n)
withn = 2^k
. By doing this, I could acquire all available tokens in 64 steps (becauseint64
has 64 bits). This is better but not yet ideal.Proposed solution
Add
TryAcquireAll
function that acquires all available tokens atomically and returns the number of tokens acquired. This allows to implement theAcquireAll
function from an example above using single call to the semaphore.