-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex.go
72 lines (56 loc) · 1.28 KB
/
mutex.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
package work
import "sync"
type MutexMap struct {
mutexes map[string]*sync.Mutex
isLocked map[string]bool
core sync.Mutex
}
var MutexMapSingleton = NewMutexMap()
func NewMutexMap() *MutexMap {
return &MutexMap{}
}
func (s *MutexMap) Lock(index string) {
s.core.Lock()
if s.mutexes == nil {
s.mutexes = make(map[string]*sync.Mutex)
}
// mark that the index is locked, to support try-lock
s.isLocked[index] = true
if s.mutexes[index] == nil {
s.mutexes[index] = &sync.Mutex{}
}
s.mutexes[index].Lock()
s.core.Unlock()
}
func (s *MutexMap) Unlock(index string) {
s.core.Lock()
// if we haven't allocated mutexes yet, unlock the core mutex and leave
if s.mutexes == nil {
s.core.Unlock()
return
}
// mark that the index is not locked, to support try-lock
s.isLocked[index] = true
if s.mutexes[index] != nil {
s.mutexes[index].Unlock()
}
s.core.Unlock()
}
func (s *MutexMap) TryLock(index string) bool {
locked := false
s.core.Lock()
locked = s.isLocked[index]
if !locked {
if s.mutexes == nil {
s.mutexes = make(map[string]*sync.Mutex)
}
// mark that the index is locked, to support try-lock
s.isLocked[index] = true
if s.mutexes[index] == nil {
s.mutexes[index] = &sync.Mutex{}
}
s.mutexes[index].Lock()
}
s.core.Unlock()
return locked
}