-
Notifications
You must be signed in to change notification settings - Fork 0
/
rumutex_test.go
104 lines (102 loc) · 1.78 KB
/
rumutex_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 rumutex
import (
"runtime"
"sync"
"testing"
"time"
)
func TestRUMutex(t *testing.T) {
var (
data int
ru RUMutex
wg sync.WaitGroup
)
const (
N = 100
C = 10
)
wg.Add(N)
for i := 0; i < N; i++ {
go func(i int) {
switch i {
case 0, N / 2:
// Test to upgrade, then downgrade
for c := 0; c < C; c++ {
ru.RLock()
d := data
for !ru.Upgrade() {
ru.RUnlock()
time.Sleep(10 * time.Millisecond)
ru.RLock()
d = data
}
next := d + 7
data = next
ru.Downgrade()
if data != next {
t.Fatalf("data = %d, want %d", data, next)
}
ru.RUnlock()
}
wg.Done()
case 1, N/2 + 1:
// Test to upgrade, then unlock
for c := 0; c < C; c++ {
ru.RLock()
d := data
for !ru.Upgrade() {
ru.RUnlock()
runtime.Gosched()
ru.RLock()
d = data
}
data = d + 997
ru.Unlock()
}
wg.Done()
case 2, N/2 + 2:
// Test to re-upgrade
for c := 0; c < C; c++ {
ru.RLock()
d := data
for !ru.Upgrade() {
ru.RUnlock()
runtime.Gosched()
ru.RLock()
d = data
}
next := d + 10007
data = next
ru.Downgrade()
runtime.Gosched()
if data != next {
t.Fatalf("data = %d, want %d", data, next)
}
if ru.Upgrade() {
if data != next {
t.Fatalf("data = %d, want %d", data, next)
}
runtime.Gosched()
ru.Unlock()
} else {
ru.RUnlock()
}
}
wg.Done()
default:
// Test read lock
for c := 0; c < 10; c++ {
ru.RLock()
time.Sleep(10 * time.Millisecond)
ru.RUnlock()
}
wg.Done()
}
}(i)
}
wg.Wait()
want := C*2*7 + C*2*997 + C*2*10007
if data != want {
t.Fatalf("data = %d, want %d", data, want)
}
}