-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathklocker.go
60 lines (52 loc) · 1.02 KB
/
klocker.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
package klocker
import (
"fmt"
"sync"
)
type KLocker interface {
Lock(key string)
Unlock(key string)
}
type KMutex struct {
mu sync.Mutex
locks map[string]*sync.Mutex
counts map[string]int
}
func (km *KMutex) Lock(key string) {
km.mu.Lock()
if km.locks == nil {
km.locks = make(map[string]*sync.Mutex)
km.counts = make(map[string]int)
}
lock, ok := km.locks[key]
if !ok {
lock = &sync.Mutex{}
km.locks[key] = lock
}
km.counts[key]++
km.mu.Unlock()
lock.Lock()
}
func (km *KMutex) Unlock(key string) {
km.mu.Lock()
defer km.mu.Unlock()
lock, ok := km.locks[key]
if !ok || km.counts[key] == 0 {
panic(fmt.Sprintf("klocker: unlock unlocked kmutex of %#v", key))
}
lock.Unlock()
km.counts[key]--
if km.counts[key] == 0 {
delete(km.locks, key)
delete(km.counts, key)
}
}
type locker struct {
kl KLocker
key string
}
func (l *locker) Lock() { l.kl.Lock(l.key) }
func (l *locker) Unlock() { l.kl.Unlock(l.key) }
func (km *KMutex) Locker(key string) sync.Locker {
return &locker{kl: km, key: key}
}