1 // Copyright 2017 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package semaphore provides a weighted semaphore implementation.
6 package semaphore // import "golang.org/x/sync/semaphore"
16 ready chan<- struct{} // Closed when semaphore acquired.
19 // NewWeighted creates a new weighted semaphore with the given
20 // maximum combined weight for concurrent access.
21 func NewWeighted(n int64) *Weighted {
22 w := &Weighted{size: n}
26 // Weighted provides a way to bound concurrent access to a resource.
27 // The callers can request access with a given weight.
28 type Weighted struct {
35 // Acquire acquires the semaphore with a weight of n, blocking until resources
36 // are available or ctx is done. On success, returns nil. On failure, returns
37 // ctx.Err() and leaves the semaphore unchanged.
39 // If ctx is already done, Acquire may still succeed without blocking.
40 func (s *Weighted) Acquire(ctx context.Context, n int64) error {
42 if s.size-s.cur >= n && s.waiters.Len() == 0 {
49 // Don't make other Acquire calls block on one that's doomed to fail.
55 ready := make(chan struct{})
56 w := waiter{n: n, ready: ready}
57 elem := s.waiters.PushBack(w)
66 // Acquired the semaphore after we were canceled. Rather than trying to
67 // fix up the queue, just pretend we didn't notice the cancelation.
70 s.waiters.Remove(elem)
80 // TryAcquire acquires the semaphore with a weight of n without blocking.
81 // On success, returns true. On failure, returns false and leaves the semaphore unchanged.
82 func (s *Weighted) TryAcquire(n int64) bool {
84 success := s.size-s.cur >= n && s.waiters.Len() == 0
92 // Release releases the semaphore with a weight of n.
93 func (s *Weighted) Release(n int64) {
98 panic("semaphore: bad release")
101 next := s.waiters.Front()
103 break // No more waiters blocked.
106 w := next.Value.(waiter)
107 if s.size-s.cur < w.n {
108 // Not enough tokens for the next waiter. We could keep going (to try to
109 // find a waiter with a smaller request), but under load that could cause
110 // starvation for large requests; instead, we leave all remaining waiters
113 // Consider a semaphore used as a read-write lock, with N tokens, N
114 // readers, and one writer. Each reader can Acquire(1) to obtain a read
115 // lock. The writer can Acquire(N) to obtain a write lock, excluding all
116 // of the readers. If we allow the readers to jump ahead in the queue,
117 // the writer will starve — there is always one token available for every
123 s.waiters.Remove(next)