-
Notifications
You must be signed in to change notification settings - Fork 80
/
locks.go
72 lines (62 loc) · 1.63 KB
/
locks.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
package updates
import (
"context"
"sync"
)
var _ LockSource = (*localLockSource)(nil)
type localLockSource struct {
sync.Mutex
wait *sync.Cond
m map[string]struct{}
}
// NewLocalLockSource provides locks backed by local concurrency primitives.
func NewLocalLockSource() *localLockSource {
l := &localLockSource{
m: make(map[string]struct{}),
}
l.wait = sync.NewCond(&l.Mutex)
return l
}
// BUG(hank) The API provided by localLockSource does not respect the parent
// context cancellation when waiting for a lock.
func (s *localLockSource) Lock(ctx context.Context, key string) (context.Context, context.CancelFunc) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
for _, exists := s.m[key]; exists; _, exists = s.m[key] {
s.wait.Wait()
}
s.m[key] = struct{}{}
c, f := context.WithCancel(ctx)
return c, s.cancelfunc(key, f)
}
func (s *localLockSource) TryLock(ctx context.Context, key string) (context.Context, context.CancelFunc) {
c, f := context.WithCancel(ctx)
s.Mutex.Lock()
defer s.Mutex.Unlock()
if _, exists := s.m[key]; exists {
f()
return c, f
}
s.m[key] = struct{}{}
return c, s.cancelfunc(key, f)
}
func (s *localLockSource) Close(ctx context.Context) error {
return nil
}
// Cancelfunc returns a CancelFunc that calls "next" and then unlocks.
func (s *localLockSource) cancelfunc(key string, next context.CancelFunc) context.CancelFunc {
return func() {
next()
s.Mutex.Lock()
defer s.Mutex.Unlock()
delete(s.m, key)
s.wait.Broadcast()
}
}
// Peek reports whether the key is locked or not.
func (s *localLockSource) peek(key string) bool {
s.Mutex.Lock()
defer s.Mutex.Unlock()
_, ok := s.m[key]
return ok
}