-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamedrwmutex.go
102 lines (91 loc) · 1.97 KB
/
namedrwmutex.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
package advsync
import (
"sync"
)
// NamedRWMutex is a named read/write mutex via sync.RWMutex
type NamedRWMutex[K comparable] struct {
mapLock sync.RWMutex
internalMap map[K]*sync.RWMutex
}
// NewNamedRWMutex create new named read/write mutex
func NewNamedRWMutex[K comparable]() *NamedRWMutex[K] {
return &NamedRWMutex[K]{
internalMap: map[K]*sync.RWMutex{},
}
}
// Unlock mutex by name
func (nm *NamedRWMutex[K]) Unlock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.RWMutex{}
nm.internalMap[slug].Unlock()
nm.mapLock.Unlock()
return
}
mutex.Unlock()
}
// UnlockSafe mutex by name
func (nm *NamedRWMutex[K]) UnlockSafe(slug K) bool {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
return false
}
return unlockSafeRW(mutex)
}
// Lock mutex by name
func (nm *NamedRWMutex[K]) Lock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.RWMutex{}
nm.internalMap[slug].Lock()
nm.mapLock.Unlock()
return
}
mutex.Lock()
}
// RUnlock mutex by name
func (nm *NamedRWMutex[K]) RUnlock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.RWMutex{}
nm.internalMap[slug].RUnlock()
nm.mapLock.Unlock()
return
}
mutex.RUnlock()
}
// RUnlockSafe mutex by name
func (nm *NamedRWMutex[K]) RUnlockSafe(slug K) bool {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
return false
}
return rUnlockSafeRW(mutex)
}
// RLock mutex by name
func (nm *NamedRWMutex[K]) RLock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.RWMutex{}
nm.internalMap[slug].RLock()
nm.mapLock.Unlock()
return
}
mutex.RLock()
}