-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.go
58 lines (47 loc) · 1.26 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
package semaphore
import (
"context"
"fmt"
"github.com/eapache/channels"
)
type ResizableSemaphore struct {
ch *channels.ResizableChannel
}
// ResizeableSemaphore returns an initialized semaphore with n slots.
func New(n int) *ResizableSemaphore {
c := channels.NewResizableChannel()
c.Resize(channels.BufferCap(n))
return &ResizableSemaphore{
ch: c,
}
}
// Acquire will attempt to acquire a slot. Will return an error if the context is canceled.
func (r *ResizableSemaphore) Acquire(ctx context.Context) error {
select {
case r.ch.In() <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Release frees up a slot.
func (r *ResizableSemaphore) Release() {
<-r.ch.Out()
}
// Resize resizes the underlying channel, increasing or reducing available slots.
func (r *ResizableSemaphore) Resize(n int) {
if n > 0 {
r.ch.Resize(channels.BufferCap(n))
}
}
// Len returns the length of the semaphore (the actively used slots)
func (r *ResizableSemaphore) Len() int {
return int(r.ch.Len())
}
// Cap returns the capacity of the semaphore (total slots available)
func (r *ResizableSemaphore) Cap() int {
return int(r.ch.Cap())
}
func (r *ResizableSemaphore) String() string {
return fmt.Sprintf("Length: %d -- Capacity: %d", r.Len(), r.Cap())
}