-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtreap_race_test.go
78 lines (67 loc) · 1.45 KB
/
treap_race_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
//go:build race
// +build race
package treap_test
import (
"sync"
"sync/atomic"
"testing"
"unsafe"
"github.com/lthibault/treap"
)
// TestRace ensures there are no data races. Only run when the -race flags is passed to
// `go test`.
func TestRace(t *testing.T) {
var root = unsafe.Pointer(&treap.Node{
Weight: 0,
Key: 0,
Value: "a",
})
var wg sync.WaitGroup
wg.Add(len(chars))
ch := make(chan struct{})
for i := 0; i < len(chars); i++ {
go func(k int, val rune) {
defer wg.Done()
<-ch // try to get as many read/writes happening at the same time
for i := 0; i < 1000; i++ {
switch {
case i&k == 0:
// Write
for {
old := (*treap.Node)(atomic.LoadPointer(&root))
if new, _ := handle.Upsert(old, k, val, k); atomic.CompareAndSwapPointer(
&root,
unsafe.Pointer(old),
unsafe.Pointer(new),
) {
break
}
}
case i&k == k-1:
// Delete
for {
old := (*treap.Node)(atomic.LoadPointer(&root))
if new := handle.Delete(old, k); atomic.CompareAndSwapPointer(
&root,
unsafe.Pointer(old),
unsafe.Pointer(new),
) {
break
}
}
default:
// Read
v, ok := handle.Get((*treap.Node)(atomic.LoadPointer(&root)), k)
if ok && v.(rune) != val {
t.Error("violation")
}
}
}
}(i, getRune(i))
}
close(ch)
wg.Wait()
}
func getRune(i int) rune {
return rune(chars[i%(len(chars)-1)])
}