-
Notifications
You must be signed in to change notification settings - Fork 1
/
locker_test.go
104 lines (93 loc) · 2.06 KB
/
locker_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
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
package namedlocker
import (
"math/rand"
"runtime"
"strconv"
"sync"
"testing"
)
func Example() {
sto := Store{}
sto.Lock("my-key")
defer sto.Unlock("my-key")
// do some work...
}
func TestStore(t *testing.T) {
sto := Store{}
testSync := func(wg *sync.WaitGroup, key string) {
defer wg.Done()
if err := sto.TryUnlock(key); err != ErrUnlockOfUnlockedKey {
t.Fatalf("TryUnlock of unlocked key should return ErrUnlockOfUnlockedKey, not %#v\n", err)
}
sto.Lock(key)
if err := sto.TryUnlock(key); err != nil {
t.Fatalf("TryUnlock of locked key should return nil, not %#v\n", err)
}
if err := sto.TryUnlock(key); err != ErrUnlockOfUnlockedKey {
t.Fatalf("TryUnlock of unlocked key should return ErrUnlockOfUnlockedKey, not %#v\n", err)
}
(func() {
defer func() {
if err := recover(); err != ErrUnlockOfUnlockedKey {
t.Fatalf("Unlock of unlocked key should panic with ErrUnlockOfUnlockedKey, not %#v\n", err)
}
}()
sto.Unlock(key)
})()
(func() {
defer func() {
if err := recover(); err != nil {
t.Fatalf("Unlock of locked key should not panic with %#v\n", err)
}
}()
sto.Lock(key)
sto.Unlock(key)
})()
}
testAsync := func(wg *sync.WaitGroup, key string) {
defer wg.Done()
sto.Lock(key)
runtime.Gosched()
sto.Unlock(key)
}
rnd := rand.New(rand.NewSource(0))
wg := &sync.WaitGroup{}
for i := 0; i < 100000; i++ {
wg.Add(1)
go testSync(wg, strconv.Itoa(rnd.Int()))
}
wg.Wait()
for i := 0; i < 100; i++ {
key := strconv.Itoa(rnd.Int())
for j := 0; j < 1000; j++ {
wg.Add(1)
go testAsync(wg, key)
}
}
wg.Wait()
if n := len(sto.refs); n != 0 {
t.Fatalf("all keys should be unlocked, but Store still contains %d locks\n", n)
}
}
func BenchmarkSync(b *testing.B) {
b.ReportAllocs()
sto := Store{}
k := ""
for i := 0; i < b.N; i++ {
sto.Lock(k)
runtime.Gosched()
sto.Unlock(k)
}
}
func BenchmarkAsync(b *testing.B) {
b.ReportAllocs()
sto := Store{}
k := ""
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sto.Lock(k)
runtime.Gosched()
sto.Unlock(k)
}
})
}