Debian Codegraph @

semaphore/semaphore.go

raw
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.
4
5 // Package semaphore provides a weighted semaphore implementation.
6 package semaphore // import "golang.org/x/sync/semaphore"
7
8 import (
9 "container/list"
10 "context"
11 "sync"
12 )
13
14 type waiter struct {
15 n int64
16 ready chan<- struct{} // Closed when semaphore acquired.
17 }
18
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}
23 return w
24 }
25
26 // Weighted provides a way to bound concurrent access to a resource.
27 // The callers can request access with a given non-negative weight.
28 type Weighted struct {
29 size int64
30 cur int64
31 mu sync.Mutex
32 waiters list.List
33 }
34
35 // Acquire acquires the semaphore with a non-negative 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.
38 func (s *Weighted) Acquire(ctx context.Context, n int64) error {
39 if n < 0 {
40 panic("semaphore: n < 0")
41 }
42 done := ctx.Done()
43
44 s.mu.Lock()
45 select {
46 case <-done:
47 // ctx becoming done has "happened before" acquiring the semaphore,
48 // whether it became done before the call began or while we were
49 // waiting for the mutex. We prefer to fail even if we could acquire
50 // the mutex without blocking.
51 s.mu.Unlock()
52 return ctx.Err()
53 default:
54 }
55 if s.size-s.cur >= n && s.waiters.Len() == 0 {
56 // Since we hold s.mu and haven't synchronized since checking done, if
57 // ctx becomes done before we return here, it becoming done must have
58 // "happened concurrently" with this call - it cannot "happen before"
59 // we return in this branch. So, we're ok to always acquire here.
60 s.cur += n
61 s.mu.Unlock()
62 return nil
63 }
64
65 if n > s.size {
66 // Don't make other Acquire calls block on one that's doomed to fail.
67 s.mu.Unlock()
68 <-done
69 return ctx.Err()
70 }
71
72 ready := make(chan struct{})
73 w := waiter{n: n, ready: ready}
74 elem := s.waiters.PushBack(w)
75 s.mu.Unlock()
76
77 select {
78 case <-done:
79 s.mu.Lock()
80 select {
81 case <-ready:
82 // Acquired the semaphore after we were canceled.
83 // Pretend we didn't and put the tokens back.
84 s.cur -= n
85 s.notifyWaiters()
86 default:
87 isFront := s.waiters.Front() == elem
88 s.waiters.Remove(elem)
89 // If we're at the front and there are extra tokens left, notify other waiters.
90 if isFront && s.size > s.cur {
91 s.notifyWaiters()
92 }
93 }
94 s.mu.Unlock()
95 return ctx.Err()
96
97 case <-ready:
98 // Acquired the semaphore. Check that ctx isn't already done.
99 // We check the done channel instead of calling ctx.Err because we
100 // already have the channel, and ctx.Err is O(n) with the nesting
101 // depth of ctx.
102 select {
103 case <-done:
104 s.Release(n)
105 return ctx.Err()
106 default:
107 }
108 return nil
109 }
110 }
111
112 // TryAcquire acquires the semaphore with a non-negative weight of n without blocking.
113 // On success, returns true. On failure, returns false and leaves the semaphore unchanged.
114 func (s *Weighted) TryAcquire(n int64) bool {
115 if n < 0 {
116 panic("semaphore: n < 0")
117 }
118 s.mu.Lock()
119 success := s.size-s.cur >= n && s.waiters.Len() == 0
120 if success {
121 s.cur += n
122 }
123 s.mu.Unlock()
124 return success
125 }
126
127 // Release releases the semaphore with a non-negative weight of n.
128 func (s *Weighted) Release(n int64) {
129 if n < 0 {
130 panic("semaphore: n < 0")
131 }
132 s.mu.Lock()
133 s.cur -= n
134 if s.cur < 0 {
135 s.mu.Unlock()
136 panic("semaphore: released more than held")
137 }
138 s.notifyWaiters()
139 s.mu.Unlock()
140 }
141
142 func (s *Weighted) notifyWaiters() {
143 for {
144 next := s.waiters.Front()
145 if next == nil {
146 break // No more waiters blocked.
147 }
148
149 w := next.Value.(waiter)
150 if s.size-s.cur < w.n {
151 // Not enough tokens for the next waiter. We could keep going (to try to
152 // find a waiter with a smaller request), but under load that could cause
153 // starvation for large requests; instead, we leave all remaining waiters
154 // blocked.
155 //
156 // Consider a semaphore used as a read-write lock, with N tokens, N
157 // readers, and one writer. Each reader can Acquire(1) to obtain a read
158 // lock. The writer can Acquire(N) to obtain a write lock, excluding all
159 // of the readers. If we allow the readers to jump ahead in the queue,
160 // the writer will starve — there is always one token available for every
161 // reader.
162 break
163 }
164
165 s.cur += w.n
166 s.waiters.Remove(next)
167 close(w.ready)
168 }
169 }