[semaphore] Add TryAcquireAll function
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:
func (p*Pool[T]) Acquire(ctx context.Context) (*T, error) {
err := p.semaphore.Acquire(ctx, 1)
if err != nil {
return nil, err
}
p.mux.Lock()
defer p.mux.Unlock()
// Pseudo-function abstracting away implementation details of the pool.
return p.takeOne()
}
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 call semaphore.TryAcquire(n) with n = 2^k. By doing this, I could acquire all available tokens in 64 steps (because int64 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 the AcquireAll function from an example above using single call to the semaphore.
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.
This PR (HEAD: cd532f29c56679a5734e0a0578811d9a8450b2cb) 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 comments slash command (e.g. /comments off)
See the Wiki page for more info
Message from Gopher Robot:
Patch Set 1:
Congratulations on opening your first change. Thank you for your contribution!
Next steps: A maintainer will review your change and provide feedback. See https://go.dev/doc/contribute#review for more info and tips to get your patch through code review.
Most changes in the Go project go through a few rounds of revision. This can be surprising to people new to the project. The careful, iterative review process is our way of helping mentor contributors and ensuring that their contributions have a lasting impact.
Please don’t reply on this GitHub thread. Visit golang.org/cl/437613. After addressing review feedback, remember to publish your drafts!
Message from Bryan Mills:
Patch Set 1: Hold+1
(1 comment)
Please don’t reply on this GitHub thread. Visit golang.org/cl/437613. After addressing review feedback, remember to publish your drafts!