-
Notifications
You must be signed in to change notification settings - Fork 0
/
rwklocker.go
96 lines (83 loc) · 1.85 KB
/
rwklocker.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
package klocker
import (
"fmt"
"sync"
)
type RWKMutex struct {
mu sync.Mutex
locks map[string]*sync.RWMutex
rCounts map[string]int
wCounts map[string]int
}
func (rw *RWKMutex) lazyInit() {
if rw.locks == nil {
rw.locks = make(map[string]*sync.RWMutex)
rw.rCounts = make(map[string]int)
rw.wCounts = make(map[string]int)
}
}
func (rw *RWKMutex) tryClean(key string) {
if rw.rCounts[key] == 0 && rw.wCounts[key] == 0 {
delete(rw.locks, key)
delete(rw.rCounts, key)
delete(rw.wCounts, key)
}
}
func (rw *RWKMutex) Lock(key string) {
rw.mu.Lock()
rw.lazyInit()
lock, ok := rw.locks[key]
if !ok {
lock = &sync.RWMutex{}
rw.locks[key] = lock
}
rw.wCounts[key]++
rw.mu.Unlock()
lock.Lock()
}
func (rw *RWKMutex) Unlock(key string) {
rw.mu.Lock()
defer rw.mu.Unlock()
lock, ok := rw.locks[key]
if !ok || rw.wCounts[key] == 0 {
panic(fmt.Sprintf("klocker: unlock unlocked rwkmutex of %#v", key))
}
lock.Unlock()
rw.wCounts[key]--
rw.tryClean(key)
}
func (rw *RWKMutex) RLock(key string) {
rw.mu.Lock()
rw.lazyInit()
lock, ok := rw.locks[key]
if !ok {
lock = &sync.RWMutex{}
rw.locks[key] = lock
}
rw.rCounts[key]++
rw.mu.Unlock()
lock.RLock()
}
func (rw *RWKMutex) RUnlock(key string) {
rw.mu.Lock()
defer rw.mu.Unlock()
lock, ok := rw.locks[key]
if !ok || rw.rCounts[key] == 0 {
panic(fmt.Sprintf("klocker: runlock unlocked rwkmutex of %#v", key))
}
lock.RUnlock()
rw.rCounts[key]--
rw.tryClean(key)
}
type rKLocker RWKMutex
func (r *rKLocker) Lock(key string) { (*RWKMutex)(r).RLock(key) }
func (r *rKLocker) Unlock(key string) { (*RWKMutex)(r).RUnlock(key) }
func (rw *RWKMutex) RKLocker() KLocker {
return (*rKLocker)(rw)
}
func (rw *RWKMutex) Locker(key string) sync.Locker {
return &locker{kl: rw, key: key}
}
func (rw *RWKMutex) RLocker(key string) sync.Locker {
return &locker{kl: rw.RKLocker(), key: key}
}