-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsemaphore.go
More file actions
92 lines (72 loc) · 1.64 KB
/
semaphore.go
File metadata and controls
92 lines (72 loc) · 1.64 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package lock
import (
"encoding/json"
"errors"
"fmt"
"sort"
)
var (
ErrExist = errors.New("holder exists")
ErrNotExist = errors.New("holder does not exist")
)
type Semaphore struct {
Index uint64 `json:"-"`
Semaphore int `json:"semaphore"`
Max int `json:"max"`
Holders []string `json:"holders"`
}
func (s *Semaphore) SetMax(max int) error {
diff := s.Max - max
s.Semaphore = s.Semaphore - diff
s.Max = s.Max - diff
return nil
}
func (s *Semaphore) String() string {
b, _ := json.Marshal(s)
return string(b)
}
func (s *Semaphore) addHolder(h string) error {
loc := sort.SearchStrings(s.Holders, h)
switch {
case loc == len(s.Holders):
s.Holders = append(s.Holders, h)
case s.Holders[loc] == h:
return ErrExist
default:
s.Holders = append(s.Holders[:loc], append([]string{h}, s.Holders[loc:]...)...)
}
return nil
}
func (s *Semaphore) removeHolder(h string) error {
loc := sort.SearchStrings(s.Holders, h)
if loc < len(s.Holders) && s.Holders[loc] == h {
s.Holders = append(s.Holders[:loc], s.Holders[loc+1:]...)
} else {
return ErrNotExist
}
return nil
}
func (s *Semaphore) Lock(h string) error {
if s.Semaphore <= 0 {
return fmt.Errorf("semaphore is at %v", s.Semaphore)
}
if err := s.addHolder(h); err != nil {
return err
}
s.Semaphore = s.Semaphore - 1
return nil
}
func (s *Semaphore) Unlock(h string) error {
if err := s.removeHolder(h); err != nil {
return err
}
s.Semaphore = s.Semaphore + 1
return nil
}
func newSemaphore() (sem *Semaphore) {
return &Semaphore{0, 1, 1, nil}
}
type holder struct {
ID string `json:"-"`
StartTime int64 `json:"startTime"`
}