-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.go
58 lines (48 loc) · 1.08 KB
/
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
package tupi
import "sync"
type keyedMutex struct {
c *sync.Cond
l sync.Locker
m map[string]int
}
func newKeyedMutex() *keyedMutex {
l := sync.Mutex{}
return &keyedMutex{c: sync.NewCond(&l), l: &l, m: make(map[string]int)}
}
func (km *keyedMutex) isLocked(key string) bool {
km.l.Lock()
defer km.l.Unlock()
_, ok := km.m[key]
return ok
}
func (km *keyedMutex) Lock(key string) {
for km.isLocked(key) {
km.c.L.Lock()
// notest
km.c.Wait()
km.c.L.Unlock()
}
km.l.Lock()
defer km.l.Unlock()
km.m[key] = 1
}
func (km *keyedMutex) Unlock(key string) {
km.l.Lock()
defer km.l.Unlock()
delete(km.m, key)
km.c.Broadcast()
}
var kmu *keyedMutex = newKeyedMutex()
// AcquireLock locks a resource based in a key When you are done you must
// release the lock with ReleaseLock()
func AcquireLock(key string) {
kmu.Lock(key)
}
// ReleaseLock releases the lock for a given resource identified by a key.
func ReleaseLock(key string) {
kmu.Unlock(key)
}
// IsLocked return a bool informing if a given resource is locked
func IsLocked(key string) bool {
return kmu.isLocked(key)
}