-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlockey.go
97 lines (79 loc) · 1.56 KB
/
lockey.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
package lockey
import (
"sync"
)
type Lockey struct {
grandMu sync.Mutex
store map[string]*storeItem
}
type storeItem struct {
mu sync.Mutex
reserve int
}
var pool = sync.Pool{
New: func() interface{} {
return new(storeItem)
},
}
// New Lockey.
//
// Creates a new Lockey.
func New() *Lockey {
return &Lockey{
grandMu: sync.Mutex{},
store: make(map[string]*storeItem),
}
}
// Lock locks the key.
//
// Creates a locked mutex for the given key.
func (l *Lockey) Lock(key string) {
l.build(key).lock()
}
// Unlock unlocks the key.
//
// Unlocks the mutex of the given key.
func (l *Lockey) Unlock(key string) {
l.destroy(key).unlock()
}
func (l *Lockey) build(key string) *storeItem {
l.grandMu.Lock()
defer l.grandMu.Unlock()
item, ok := l.store[key]
if !ok {
// If there is no item, get one from the pool.
item = pool.Get().(*storeItem)
l.store[key] = item
}
// A new reservation has been made.
// Increase the count.
item.reserve++
return item
}
func (l *Lockey) destroy(key string) *storeItem {
l.grandMu.Lock()
defer l.grandMu.Unlock()
item, ok := l.store[key]
if !ok {
panic("There is no such lock for key: " + key)
}
item.reserve--
// Remove item from the store if there is no reservation for the key.
if !item.isReserved() {
// Put it back to pool.
pool.Put(item)
// Remove from the store.
delete(l.store, key)
}
return item
}
func (i *storeItem) lock() {
i.mu.Lock()
}
func (i *storeItem) unlock() {
i.mu.Unlock()
}
// Is there any reservation?
func (i *storeItem) isReserved() bool {
return i.reserve > 0
}