-
Notifications
You must be signed in to change notification settings - Fork 0
/
semp.go
52 lines (43 loc) · 763 Bytes
/
semp.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 semp
import (
"errors"
"sync"
)
type NotifyFunc func()
var (
ErrCannotAcquire = errors.New("cannot acquire semaphore")
)
type Semp struct {
weight uint32
count uint32
ch chan bool
mu *sync.Mutex
notify NotifyFunc
}
func New(w uint, n NotifyFunc) *Semp {
return &Semp{
weight: uint32(w),
count: uint32(0),
ch: make(chan bool, 1),
mu: &sync.Mutex{},
notify: n,
}
}
// How to tackle this one
// should we have slots for this ?
func (s *Semp) Acquire(i int) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.count+uint32(i) > s.weight {
return ErrCannotAcquire
}
s.count += uint32(i)
return nil
}
func (s *Semp) Release(i int) error {
s.mu.Lock()
defer s.mu.Unlock()
s.count--
go s.notify()
return nil
}