-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
74 lines (63 loc) · 1.48 KB
/
example_test.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
package comutex_test
import (
"context"
"fmt"
"sync"
"github.com/josephbuchma/comutex"
)
// IntKVStore is a simple shared stirng=>int KV store.
// Even though all of its methods are locking mutex,
// Get method is used inside of Sum,
// and Has is used inside of Insert and Update - and it doesn't cause a deadlock.
type IntKVStore struct {
mu sync.RWMutex
m map[string]int
}
func (s *IntKVStore) Get(ctx context.Context, key string) int {
_, unlock := comutex.RLock(ctx, &s.mu)
defer unlock()
return s.m[key]
}
func (s *IntKVStore) Has(ctx context.Context, key string) bool {
_, unlock := comutex.RLock(ctx, &s.mu)
defer unlock()
_, ok := s.m[key]
return ok
}
func (s *IntKVStore) Insert(ctx context.Context, key string, v int) bool {
ctx, unlock := comutex.MustLock(ctx, &s.mu)
defer unlock()
if s.Has(ctx, key) {
return false
}
s.m[key] = v
return true
}
func (s *IntKVStore) Update(ctx context.Context, key string, v int) bool {
ctx, unlock := comutex.MustLock(ctx, &s.mu)
defer unlock()
if s.Has(ctx, key) {
s.m[key] = v
return true
}
return false
}
func (s *IntKVStore) Sum(ctx context.Context, keys ...string) int {
ctx, unlock := comutex.RLock(ctx, &s.mu)
defer unlock()
r := 0
for _, key := range keys {
r += s.Get(ctx, key)
}
return r
}
func Example() {
ctx := context.Background()
s := &IntKVStore{m: map[string]int{}}
s.Insert(ctx, "a", 1)
s.Insert(ctx, "b", 2)
s.Update(ctx, "b", 3)
fmt.Println("a+b:", s.Sum(ctx, "a", "b"))
// Output:
// a+b: 4
}