-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
mapmutex.go
39 lines (32 loc) · 739 Bytes
/
mapmutex.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
package timeliner
import "sync"
// Modified from https://medium.com/@petrlozhkin/kmutex-lock-mutex-by-unique-id-408467659c24
type mapMutex struct {
cond *sync.Cond
set map[interface{}]struct{}
}
func newMapMutex() *mapMutex {
return &mapMutex{
cond: sync.NewCond(new(sync.Mutex)),
set: make(map[interface{}]struct{}),
}
}
func (mmu *mapMutex) Lock(key interface{}) {
mmu.cond.L.Lock()
defer mmu.cond.L.Unlock()
for mmu.locked(key) {
mmu.cond.Wait()
}
mmu.set[key] = struct{}{}
return
}
func (mmu *mapMutex) Unlock(key interface{}) {
mmu.cond.L.Lock()
defer mmu.cond.L.Unlock()
delete(mmu.set, key)
mmu.cond.Broadcast()
}
func (mmu *mapMutex) locked(key interface{}) (ok bool) {
_, ok = mmu.set[key]
return
}