-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.go
77 lines (70 loc) · 1.66 KB
/
semaphore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package async
import "slices"
// Semaphore provides a way to bound asynchronous access to a resource.
// The callers can request access with a given weight.
//
// Note that this Semaphore type does not provide backpressure for spawning
// a lot of Tasks. One should instead look for a sync implementation.
//
// A Semaphore must not be shared by more than one [Executor].
type Semaphore struct {
size int64
cur int64
waiters []*waiter
}
type waiter struct {
Signal
n int64
}
// NewSemaphore creates a new weighted semaphore with the given maximum
// combined weight.
func NewSemaphore(n int64) *Semaphore {
return &Semaphore{size: n}
}
// Acquire returns a [Task] that awaits until a weight of n is acquired from
// the semaphore, and then ends.
func (s *Semaphore) Acquire(n int64) Task {
if n < 0 {
panic("async(Semaphore): negative weight")
}
return func(co *Coroutine) Result {
if s.size-s.cur < n {
if n > s.size {
return co.Await() // Impossible to success.
}
w := &waiter{n: n}
s.waiters = append(s.waiters, w)
co.Watch(w)
return co.Yield(NoOperation())
}
s.cur += n
return co.End()
}
}
// Release releases the semaphore with a weight of n.
//
// One should only call this method in a [Task] function.
func (s *Semaphore) Release(n int64) {
if n < 0 {
panic("async(Semaphore): negative weight")
}
if s.cur >= 0 {
s.cur -= n
}
if s.cur < 0 {
panic("async(Semaphore): released more than held")
}
s.notifyWaiters()
}
func (s *Semaphore) notifyWaiters() {
i := 0
for i = range s.waiters {
w := s.waiters[i]
if s.size-s.cur < w.n {
break
}
s.cur += w.n
w.Notify()
}
s.waiters = slices.Delete(s.waiters, 0, i)
}