-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashlock.go
More file actions
94 lines (85 loc) · 2.07 KB
/
hashlock.go
File metadata and controls
94 lines (85 loc) · 2.07 KB
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
package hashlock
import (
"strings"
"sync"
"time"
)
// HashLock keeps a hashmap with unique keys and lock conditions
// Also has a rw mutex for the hashmap to avoid race conditions between threads
// If timeout is set the lock is unlocked after the given time
type HashLock struct {
locks map[string]chan bool
mapLock *sync.RWMutex
timeout time.Duration
}
// New initializes a new HashLock
func (l *HashLock) New(d time.Duration) *HashLock {
l.locks = make(map[string]chan bool)
l.mapLock = &sync.RWMutex{}
if d > 0 {
l.timeout = d
} else {
l.timeout = 1 * time.Second
}
return l
}
// getLock returns a lock condition for the provided key
func (l *HashLock) getLock(key string) chan bool {
l.mapLock.RLock()
_, found := l.locks[key]
if !found {
//remove the read lock and lock for writes
l.mapLock.RUnlock()
l.mapLock.Lock()
defer l.mapLock.Unlock()
l.locks[key] = make(chan bool, 1)
} else {
defer l.mapLock.RUnlock()
}
return l.locks[key]
}
// Lock locks the provided key for rw
func (l *HashLock) Lock(key string) {
l.getLock(key) <- true
//unlock after one second no need to wait more
if l.timeout > 0 {
time.AfterFunc(1*l.timeout, func() {
// loop to handle more than one locks
for i := 0; i < len(l.getLock(key)); i++ {
<-l.getLock(key)
}
})
}
}
// Unlock unlocks the provided key for rw
func (l *HashLock) Unlock(key string) {
if len(l.getLock(key)) > 0 {
<-l.getLock(key)
}
}
// GetLockKey provides a pattern for creating keys from string arrays
func (l *HashLock) GetLockKey(args []string) string {
return strings.Join(args, "-")
}
// DeleteKey removes a key from hashmap with locks
func (l *HashLock) DeleteKey(key string) {
var found bool
if _, found = l.locks[key]; found {
l.mapLock.Lock()
defer l.mapLock.Unlock()
delete(l.locks, key)
}
}
// Empty removes all non used keys from hashmap to release memory
func (l *HashLock) Empty(force bool) bool {
l.mapLock.Lock()
defer l.mapLock.Unlock()
for k, v := range l.locks {
if len(v) == 0 || force {
delete(l.locks, k)
} else {
return false
}
}
return true
}