-
Notifications
You must be signed in to change notification settings - Fork 0
/
sem.go
52 lines (43 loc) · 1.13 KB
/
sem.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
// Package sem implements a semaphore, allowing to limit the concurrency of goroutines.
package sem
type Sem chan struct{}
// New makes a new semaphore with a given limit on concurrency.
func New(n int) Sem {
return make(chan struct{}, n)
}
func (s Sem) Cap() int {
return cap(s)
}
// Acquire marks the start of a limited concurrency section.
func (s Sem) Acquire() {
s <- struct{}{}
}
// Release marks the end of a limited concurrency section.
func (s Sem) Release() {
<-s
}
// Executes the given function with a limit on concurrency.
func (s Sem) Exec(f func()) {
s.Acquire()
defer s.Release()
f()
}
// Executes the given function with a limit on concurrency, returning an error.
func (s Sem) Exece(f func() error) error {
s.Acquire()
defer s.Release()
return f()
}
// Executes the given function with a limit on concurrency, returning a function.
func (s Sem) Execfun(f func() func()) func() {
s.Acquire()
defer s.Release()
return f()
}
// Acquires all the spots on the semaphore, effectively making sure that no other functions can execute.
func (s Sem) Drain() {
n := cap(s)
for i := 0; i < n; i++ {
s <- struct{}{}
}
}