-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
105 lines (91 loc) · 1.66 KB
/
lock.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package ds
import (
"fmt"
"github.com/qizong007/ware-kv/warekv/util"
"sync"
"time"
"unsafe"
)
type Lock struct {
Base
State bool
TimeLimit int64 // if hit TimeLimit, the lock will release
Guid string
rw sync.RWMutex
}
var lockStructMemUsage int
func init() {
lockStructMemUsage = int(unsafe.Sizeof(Lock{}))
}
type LockView struct {
IsLocked bool `json:"is_locked"`
TimeLeft int64 `json:"time_left"`
}
func (l *Lock) GetValue() interface{} {
l.rw.RLock()
defer l.rw.RUnlock()
var t int64 = 0
if l.State {
t = l.UpdateTime + l.TimeLimit - time.Now().Unix()
if t < 0 {
t = 0
}
}
return &LockView{
IsLocked: l.State,
TimeLeft: t,
}
}
func (l *Lock) Size() int {
size := lockStructMemUsage
if l.ExpireTime != nil {
size += 8
}
size += len(l.Guid)
return size
}
func MakeLock() *Lock {
return &Lock{
Base: *NewBase(util.LockDS),
}
}
func (l *Lock) Lock(t int64, guid string) error {
if l.isLocked() {
return fmt.Errorf("LockFailed")
}
l.rw.Lock()
defer l.rw.Unlock()
l.Update()
l.State = true
l.TimeLimit = t
l.Guid = guid
// time over, release lock
time.AfterFunc(time.Second*time.Duration(t), func() {
_ = l.Unlock(l.Guid)
})
return nil
}
func (l *Lock) Unlock(guid string) error {
if !l.isLocked() {
return fmt.Errorf("UnlockFailed")
}
if !l.checkLockKeeper(guid) {
return fmt.Errorf("NotTheCorrectLockKeeper")
}
l.rw.Lock()
defer l.rw.Unlock()
l.Update()
l.State = false
l.TimeLimit = 0
return nil
}
func (l *Lock) isLocked() bool {
l.rw.RLock()
defer l.rw.RUnlock()
return l.State
}
func (l *Lock) checkLockKeeper(guid string) bool {
l.rw.RLock()
defer l.rw.RUnlock()
return l.Guid == guid
}