[semaphore] Add TryAcquireAll function#19
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
d16bec7 to
cd532f2
Compare
|
This PR (HEAD: cd532f2) has been imported to Gerrit for code review. Please visit https://go-review.googlesource.com/c/sync/+/437613 to see it. Tip: You can toggle comments from me using the |
|
Message from Gopher Robot: Patch Set 1: Congratulations on opening your first change. Thank you for your contribution! Next steps: Most changes in the Go project go through a few rounds of revision. This can be Please don’t reply on this GitHub thread. Visit golang.org/cl/437613. |
|
Message from Bryan Mills: Patch Set 1: Hold+1 (1 comment) Please don’t reply on this GitHub thread. Visit golang.org/cl/437613. |
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
AcquireAllthat 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 (becauseint64has 64 bits). This is better but not yet ideal.Proposed solution
Add
TryAcquireAllfunction that acquires all available tokens atomically and returns the number of tokens acquired. This allows to implement theAcquireAllfunction from an example above using single call to the semaphore.