-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamedmutex.go
More file actions
59 lines (53 loc) · 1.11 KB
/
namedmutex.go
File metadata and controls
59 lines (53 loc) · 1.11 KB
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
package advsync
import (
"sync"
)
// NamedMutex is a named mutex via sync.RWMutex
type NamedMutex[K comparable] struct {
mapLock sync.RWMutex
internalMap map[K]*sync.Mutex
}
// NewNamedMutex create new named mutex
func NewNamedMutex[K comparable]() *NamedMutex[K] {
return &NamedMutex[K]{
internalMap: map[K]*sync.Mutex{},
}
}
// Unlock mutex by name
func (nm *NamedMutex[K]) Unlock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.Mutex{}
nm.internalMap[slug].Unlock()
nm.mapLock.Unlock()
return
}
mutex.Unlock()
}
// UnlockSafe mutex by name
func (nm *NamedMutex[K]) UnlockSafe(slug K) bool {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
return false
}
return unlockSafe(mutex)
}
// Lock mutex by name
func (nm *NamedMutex[K]) Lock(slug K) {
nm.mapLock.RLock()
mutex, ok := nm.internalMap[slug]
nm.mapLock.RUnlock()
if !ok {
nm.mapLock.Lock()
nm.internalMap[slug] = &sync.Mutex{}
nm.internalMap[slug].Lock()
nm.mapLock.Unlock()
return
}
mutex.Lock()
}