forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keylock.go
48 lines (39 loc) · 964 Bytes
/
keylock.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
package util
import "sync"
// Allows to lock by string key
type KeyLock struct {
giantLock sync.RWMutex
locks map[string]*sync.Mutex
}
// NewKeyLock creates new instance of KeyLock
func NewKeyLock() *KeyLock {
return &KeyLock{
giantLock: sync.RWMutex{},
locks: map[string]*sync.Mutex{},
}
}
func (keyLock *KeyLock) getLock(key string) *sync.Mutex {
keyLock.giantLock.RLock()
if lock, ok := keyLock.locks[key]; ok {
keyLock.giantLock.RUnlock()
return lock
}
keyLock.giantLock.RUnlock()
keyLock.giantLock.Lock()
if lock, ok := keyLock.locks[key]; ok {
keyLock.giantLock.Unlock()
return lock
}
lock := &sync.Mutex{}
keyLock.locks[key] = lock
keyLock.giantLock.Unlock()
return lock
}
// Lock blocks goroutine using key specific mutex
func (keyLock *KeyLock) Lock(key string) {
keyLock.getLock(key).Lock()
}
// Unlock releases key specific mutex
func (keyLock *KeyLock) Unlock(key string) {
keyLock.getLock(key).Unlock()
}