Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions semaphore/semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,21 @@ func NewWeighted(n int64) *Weighted {
}

// Weighted provides a way to bound concurrent access to a resource.
// The callers can request access with a given weight.
// The callers can request access with a given non-negative weight.
type Weighted struct {
size int64
cur int64
mu sync.Mutex
waiters list.List
}

// Acquire acquires the semaphore with a weight of n, blocking until resources
// Acquire acquires the semaphore with a non-negative weight of n, blocking until resources
// are available or ctx is done. On success, returns nil. On failure, returns
// ctx.Err() and leaves the semaphore unchanged.
func (s *Weighted) Acquire(ctx context.Context, n int64) error {
if n < 0 {
panic("semaphore: n < 0")
}
done := ctx.Done()

s.mu.Lock()
Expand Down Expand Up @@ -106,9 +109,12 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error {
}
}

// TryAcquire acquires the semaphore with a weight of n without blocking.
// TryAcquire acquires the semaphore with a non-negative weight of n without blocking.
// On success, returns true. On failure, returns false and leaves the semaphore unchanged.
func (s *Weighted) TryAcquire(n int64) bool {
if n < 0 {
panic("semaphore: n < 0")
}
s.mu.Lock()
success := s.size-s.cur >= n && s.waiters.Len() == 0
if success {
Expand All @@ -118,8 +124,11 @@ func (s *Weighted) TryAcquire(n int64) bool {
return success
}

// Release releases the semaphore with a weight of n.
// Release releases the semaphore with a non-negative weight of n.
func (s *Weighted) Release(n int64) {
if n < 0 {
panic("semaphore: n < 0")
}
s.mu.Lock()
s.cur -= n
if s.cur < 0 {
Expand Down
33 changes: 33 additions & 0 deletions semaphore/semaphore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,39 @@ func TestWeightedPanic(t *testing.T) {
w.Release(1)
}

func TestWeightedNegativeWeightPanic(t *testing.T) {
t.Parallel()

ctx := context.Background()
w := semaphore.NewWeighted(1)
func() {
defer func() {
if recover() == nil {
t.Fatal("Acquire with negative weight did not panic")
}
}()
w.Acquire(ctx, -1)
}()

func() {
defer func() {
if recover() == nil {
t.Fatal("TryAcquire with negative weight did not panic")
}
}()
w.TryAcquire(-1)
}()

func() {
defer func() {
if recover() == nil {
t.Fatal("Release with negative weight did not panic")
}
}()
w.Release(-1)
}()
}

func TestWeightedTryAcquire(t *testing.T) {
t.Parallel()

Expand Down