-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.go
60 lines (43 loc) · 796 Bytes
/
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
package keylock
import (
"sync"
)
type keyLock struct {
localLockMap map[string]*lock
globalLock sync.Mutex
}
type lock struct {
mux *sync.Mutex
refCount int
}
func NewKeyLock() *keyLock {
return &keyLock{localLockMap: map[string]*lock{}}
}
func (km *keyLock) Lock(key string) {
km.globalLock.Lock()
wl, locked := km.localLockMap[key]
if !locked {
wl = &lock{
mux: new(sync.Mutex),
refCount: 0,
}
km.localLockMap[key] = wl
}
wl.refCount++
km.globalLock.Unlock()
wl.mux.Lock()
}
func (km *keyLock) Unlock(key string) {
km.globalLock.Lock()
wl, locked := km.localLockMap[key]
if !locked {
km.globalLock.Unlock()
return
}
wl.refCount--
if wl.refCount <= 0 {
delete(km.localLockMap, key)
}
km.globalLock.Unlock()
wl.mux.Unlock()
}