/
mlock.go
64 lines (52 loc) · 850 Bytes
/
mlock.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
package tool
import "sync"
var m *mlock
type mlock struct {
lock sync.RWMutex
locks map[string]*sync.RWMutex
}
func initmlock() {
m = new(mlock)
m.locks = make(map[string]*sync.RWMutex)
}
func init() {
initmlock()
}
func getLock(key string) *sync.RWMutex {
m.lock.RLock()
lock, ok := m.locks[key]
m.lock.RUnlock()
if ok {
return lock
}
m.lock.Lock()
defer m.lock.Unlock()
lock, ok = m.locks[key]
if ok {
return lock
}
m.locks[key] = new(sync.RWMutex)
return m.locks[key]
}
func Lock(key string) {
getLock(key).Lock()
}
func Unlock(key string) {
getLock(key).Unlock()
}
func RLock(key string) {
getLock(key).RLock()
}
func RUnlock(key string) {
getLock(key).RUnlock()
}
func Use(key string, f func()) {
Lock(key)
defer Unlock(key)
f()
}
func RUse(key string, f func()) {
RLock(key)
defer RUnlock(key)
f()
}