-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkeylock.go
64 lines (53 loc) · 956 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package keylock
import (
"sort"
"sync"
)
type KeyLock struct {
mtx sync.Mutex
locks map[string]chan struct{}
}
func New() *KeyLock {
return &KeyLock{
locks: make(map[string]chan struct{}),
}
}
func (l *KeyLock) LockKeys(keys []string, cancel <-chan struct{}) (canceled bool, unlock func()) {
sort.Strings(keys)
acquired := make([]chan struct{}, 0)
unlock = func() {
l.mtx.Lock()
for key := range l.locks {
delete(l.locks, key)
}
l.mtx.Unlock()
for _, lock := range acquired {
close(lock)
}
}
for _, key := range keys {
for {
l.mtx.Lock()
otherLock, alreadyLocked := l.locks[key]
lock := make(chan struct{})
if !alreadyLocked {
l.locks[key] = lock
}
l.mtx.Unlock()
if !alreadyLocked {
acquired = append(acquired, lock)
break
}
select {
case <-cancel:
unlock()
canceled = true
return
case <-otherLock:
continue
}
}
}
canceled = false
return
}