-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspinlock_test.go
More file actions
94 lines (87 loc) · 1.48 KB
/
spinlock_test.go
File metadata and controls
94 lines (87 loc) · 1.48 KB
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
package spinlock
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func testLock(threads, n int, l sync.Locker) time.Duration {
var wg sync.WaitGroup
wg.Add(threads)
var count1 int
var count2 int
start := time.Now()
for i := 0; i < threads; i++ {
go func() {
for i := 0; i < n; i++ {
l.Lock()
count1++
count2 += 2
l.Unlock()
}
wg.Done()
}()
}
wg.Wait()
dur := time.Since(start)
if count1 != threads*n {
panic("mismatch")
}
if count2 != threads*n*2 {
panic("mismatch")
}
return dur
}
func TestSpinLock(t *testing.T) {
// 调整vscode的配置go.testTimeout时间
cases := []struct {
name string
threads int
n int
l sync.Locker
}{
{
name: "spinlock[1]",
threads: 1,
n: 1000000,
l: NewSpinLock(),
},
{
name: "mutex[1]",
threads: 1,
n: 1000000,
l: &sync.Mutex{},
},
{
name: "spinlock[4]",
threads: 4,
n: 1000000,
l: NewSpinLock(),
},
{
name: "mutex[4]",
threads: 4,
n: 1000000,
l: &sync.Mutex{},
},
{
name: "spinlock[8]",
threads: 8,
n: 1000000,
l: NewSpinLock(),
},
{
name: "mutex[8]",
threads: 8,
n: 1000000,
l: &sync.Mutex{},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ti := testLock(tc.threads, tc.n, tc.l)
assert.NotNil(t, ti)
t.Logf("%s %4.0fms\n", tc.name, ti.Seconds()*1000)
})
}
}