File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ package work
2+
3+ import "sync"
4+
5+ type MutexMap struct {
6+ mutexes map [string ]* sync.Mutex
7+ isLocked map [string ]bool
8+ core sync.Mutex
9+ }
10+
11+ var MutexMapSingleton = MutexMap {}
12+
13+ func (s * MutexMap ) Lock (index string ) {
14+ s .core .Lock ()
15+ if s .mutexes == nil {
16+ s .mutexes = make (map [string ]* sync.Mutex )
17+ }
18+
19+ // mark that the index is locked, to support try-lock
20+ s .isLocked [index ] = true
21+
22+ if s .mutexes [index ] == nil {
23+ s .mutexes [index ] = & sync.Mutex {}
24+ }
25+ s .mutexes [index ].Lock ()
26+ s .core .Unlock ()
27+ }
28+
29+ func (s * MutexMap ) Unlock (index string ) {
30+ s .core .Lock ()
31+
32+ // if we haven't allocated mutexes yet, unlock the core mutex and leave
33+ if s .mutexes == nil {
34+ s .core .Unlock ()
35+ return
36+ }
37+
38+ // mark that the index is not locked, to support try-lock
39+ s .isLocked [index ] = true
40+
41+ if s .mutexes [index ] != nil {
42+ s .mutexes [index ].Unlock ()
43+ }
44+ s .core .Unlock ()
45+ }
46+
47+ func (s * MutexMap ) TryLock (index string ) bool {
48+ locked := false
49+ s .core .Lock ()
50+ locked = s .isLocked [index ]
51+
52+ if ! locked {
53+ if s .mutexes == nil {
54+ s .mutexes = make (map [string ]* sync.Mutex )
55+ }
56+
57+ // mark that the index is locked, to support try-lock
58+ s .isLocked [index ] = true
59+
60+ if s .mutexes [index ] == nil {
61+ s .mutexes [index ] = & sync.Mutex {}
62+ }
63+ s .mutexes [index ].Lock ()
64+ }
65+
66+ s .core .Unlock ()
67+ return locked
68+ }
You can’t perform that action at this time.
0 commit comments