-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlock.go
103 lines (85 loc) · 1.58 KB
/
mlock.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
103
package mlock
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
)
var (
cleanInterval = 30 * time.Minute
once sync.Once
)
var mLock multiLock
type multiLock struct {
cLck sync.RWMutex
l sync.Map
}
type lockDetails struct {
lck *sync.Mutex
c int64
}
func KeepClean(intervalInMinute *time.Duration) {
once.Do(func() {
if intervalInMinute != nil {
cleanInterval = *intervalInMinute
}
go func() {
ticker := time.NewTicker(cleanInterval)
for {
<-ticker.C
func() {
mLock.cLck.Lock()
defer mLock.cLck.Unlock()
mLock.l.Range(func(key, value any) bool {
ld := value.(*lockDetails)
if ld.c == 0 {
mLock.l.Delete(key)
}
return true
})
}()
}
}()
})
}
func Lock(keys ...interface{}) {
mLock.cLck.RLock()
defer mLock.cLck.RUnlock()
uKey := getKey(keys)
lDetails := getOrStoreLock(uKey)
atomic.AddInt64(&lDetails.c, 1)
lDetails.lck.Lock()
}
func Unlock(keys ...interface{}) {
uKey := getKey(keys)
lDetails := getLock(uKey)
if lDetails == nil {
return
}
lDetails.lck.Unlock()
atomic.AddInt64(&lDetails.c, -1)
}
func getOrStoreLock(key string) *lockDetails {
ld, _ := mLock.l.LoadOrStore(key, &lockDetails{
lck: &sync.Mutex{},
})
return ld.(*lockDetails)
}
func getLock(key string) *lockDetails {
ld, ok := mLock.l.Load(key)
if !ok {
return nil
}
return ld.(*lockDetails)
}
func getKey(keys ...interface{}) string {
if len(keys) == 0 {
panic("mLock key necessary")
}
k := []string{}
for _, key := range keys {
k = append(k, fmt.Sprint(key))
}
return strings.Join(k, "_")
}