-
Notifications
You must be signed in to change notification settings - Fork 8
/
locker.go
108 lines (89 loc) · 2.43 KB
/
locker.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
Package locker is a simple package to manage named ReadWrite mutexes. These
appear to be especially useful for synchronizing access to session based
information in web applications.
The common use case is to use the package level functions, which use a package
level set of locks (safe to use from multiple goroutines simultaneously).
However, you may also create a new separate set of locks.
All locks are implemented with read-write mutexes. To use them like a regular
mutex, simply ignore the RLock/RUnlock functions.
*/
package locker
// BUG(burntsushi): The locker here can grow without bound in long running
// programs. Since it's intended to be used in web applications, this is a
// major problem. Figure out a way to keep the locker lean.
import (
"fmt"
"sync"
)
// Locker represents the set of named ReadWrite mutexes. It is safe to access
// from multiple goroutines simultaneously.
type Locker struct {
locks map[string]*sync.RWMutex
locksRW *sync.RWMutex
}
var locker *Locker
func init() {
locker = NewLocker()
}
func Lock(key string) { locker.Lock(key) }
func Unlock(key string) { locker.Unlock(key) }
func RLock(key string) { locker.RLock(key) }
func RUnlock(key string) { locker.RUnlock(key) }
func NewLocker() *Locker {
return &Locker{
locks: make(map[string]*sync.RWMutex),
locksRW: new(sync.RWMutex),
}
}
func (lker *Locker) Lock(key string) {
lk, ok := lker.getLock(key)
if !ok {
lk = lker.newLock(key)
}
lk.Lock()
}
func (lker *Locker) Unlock(key string) {
lk, ok := lker.getLock(key)
if !ok {
panic(fmt.Errorf("BUG: Lock for key '%s' not initialized.", key))
}
lk.Unlock()
}
func (lker *Locker) RLock(key string) {
lk, ok := lker.getLock(key)
if !ok {
lk = lker.newLock(key)
}
lk.RLock()
}
func (lker *Locker) RUnlock(key string) {
lk, ok := lker.getLock(key)
if !ok {
panic(fmt.Errorf("BUG: Lock for key '%s' not initialized.", key))
}
lk.RUnlock()
}
func (lker *Locker) newLock(key string) *sync.RWMutex {
lker.locksRW.Lock()
defer lker.locksRW.Unlock()
if lk, ok := lker.locks[key]; ok {
return lk
}
lk := new(sync.RWMutex)
lker.locks[key] = lk
return lk
}
func (lker *Locker) getLock(key string) (*sync.RWMutex, bool) {
lker.locksRW.RLock()
defer lker.locksRW.RUnlock()
lock, ok := lker.locks[key]
return lock, ok
}
func (lker *Locker) deleteLock(key string) {
lker.locksRW.Lock()
defer lker.locksRW.Unlock()
if _, ok := lker.locks[key]; ok {
delete(lker.locks, key)
}
}