-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
66 lines (52 loc) · 948 Bytes
/
lock.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
package mlcache
import (
"sync"
"time"
)
type KeyLock struct {
Mu *sync.Mutex
Lock map[string]chan struct{}
}
func newKeyLock(size int64) *KeyLock {
return &KeyLock{
Mu: new(sync.Mutex),
Lock: make(map[string]chan struct{}, size),
}
}
func (kl *KeyLock) getVal(key string) chan struct{} {
kl.Mu.Lock()
defer kl.Mu.Unlock()
var ch chan struct{}
var ok bool
ch, ok = kl.Lock[key]
if !ok {
ch = make(chan struct{}, 1)
kl.Lock[key] = ch
}
return ch
}
func (kl *KeyLock) TimeoutLock(key string, timeout time.Duration) bool {
ch := kl.getVal(key)
t := time.NewTimer(timeout)
defer t.Stop()
select {
case ch <- struct{}{}:
return true
case <-t.C:
return false
}
}
func (kl *KeyLock) Trylock(key string) bool {
ch := kl.getVal(key)
select {
case ch <- struct{}{}:
return true
default:
return false
}
}
func (kl *KeyLock) Unlock(key string) {
kl.Mu.Lock()
defer kl.Mu.Unlock()
<-kl.Lock[key]
}