Skip to content

proposal: x/sync/semaphore: expose the size  #53940

@dsnet

Description

@dsnet

In my usages of sempahore, I'm doing something like:

const maxWeight = ...
sema := semaphore.NewWeighted(maxWeight)
...
for ... {
    size := object.Size()
    if size > maxWeight {
        // Object is too large to fit in memory, switch to a streaming mode.
        object.StreamingMode(true)
        size = maxWeight // use the maximum weight to have exclusive lock over semaphore
    }
    sema.Acquire(size)
    go func() {
        defer sema.Release(size)
        ...
    }
}

You will notice that I'm passing around both sema and maxWeight. However, this is a somewhat unnecessary since the unexported sema.size field is exactly the information I need.

I propose adding a Capacity method:

// Capacity returns the maximum combined weight this semaphore is constructed with.
func (s *Weighted) Capacity() int64 {
    return s.size
}

Alternative names: Weight, MaxWeight, MaxSize. We should choose a name that would not prevent the possible future addition of a something like Length where we return the value of s.cur. The names of Length of Capacity would match the names of len(c) and cap(c) when a channel is used a semaphore.

\cc @jba

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions