Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: x/sync/semaphore: Add TryAcquireAll function #56026

Open
jan-dubsky opened this issue Oct 4, 2022 · 3 comments
Open

proposal: x/sync/semaphore: Add TryAcquireAll function #56026

jan-dubsky opened this issue Oct 4, 2022 · 3 comments
Labels
Milestone

Comments

@jan-dubsky
Copy link

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:

@gopherbot gopherbot added this to the Proposal milestone Oct 4, 2022
@ianlancetaylor
Copy link
Contributor

CC @jba

@jan-dubsky
Copy link
Author

It feels that this issue is not moving anywhere. Is there something I can do to push it forward?

@ianlancetaylor
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

3 participants