Description
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:
Metadata
Metadata
Assignees
Type
Projects
Status