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.
Proposed implementation of this method is available here: - GitHub - Googlesource
Comment From: ianlancetaylor
CC @jba
Comment From: jan-dubsky
It feels that this issue is not moving anywhere. Is there something I can do to push it forward?
Comment From: ianlancetaylor
This proposal is in the incoming queue, along with over 200 other proposals (see https://github.com/orgs/golang/projects/17). We'll get to it. Sorry for the delay, but there are lots of proposals. You can follow the proposal process in general at #33502.
Comment From: seankhliao
This is probably better served by #53940