-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreslock.go
88 lines (78 loc) · 1.78 KB
/
reslock.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
78
79
80
81
82
83
84
85
86
87
88
package lock
import (
"context"
"go.uber.org/zap"
)
type reslock struct {
log *zap.Logger
// mutex with timeout based on a channel
operationMu chan struct{}
// lock methods should prevent calling release method, and at the same time
// release should be allowed only on the safe spots, e.g., waiting on notification
releaseMu chan struct{}
}
func newResLock(log *zap.Logger) *reslock {
rl := &reslock{
log: log,
// operation - lock/readLock/Release/UpdateTTL
operationMu: make(chan struct{}, 1),
// Should be freed to Release lock, updateTTL
releaseMu: make(chan struct{}, 1),
}
// arm
rl.operationMu <- struct{}{}
rl.releaseMu <- struct{}{}
return rl
}
func (r *reslock) lock(ctx context.Context) bool {
select {
case <-r.operationMu:
select {
case <-r.releaseMu:
case <-ctx.Done():
select {
case r.operationMu <- struct{}{}:
default:
r.log.DPanic("failed to put operation semaphore back, channel is full")
}
return false
}
return true
case <-ctx.Done():
return false
}
}
func (r *reslock) unlock() {
select {
case r.operationMu <- struct{}{}:
select {
case r.releaseMu <- struct{}{}:
default:
r.log.DPanic("failed to put release semaphore back, channel is full")
}
default:
r.log.DPanic("failed to put operation semaphore back, channel is full")
}
}
func (r *reslock) unlockOperation() {
select {
case r.operationMu <- struct{}{}:
default:
r.log.DPanic("failed to put operation semaphore back, channel is full")
}
}
func (r *reslock) unlockRelease() {
select {
case r.releaseMu <- struct{}{}:
default:
r.log.DPanic("failed to put release semaphore back, channel is full")
}
}
func (r *reslock) lockRelease(ctx context.Context) bool {
select {
case <-r.releaseMu:
return true
case <-ctx.Done():
return false
}
}