-
Notifications
You must be signed in to change notification settings - Fork 6
/
mutex_test.go
103 lines (93 loc) · 1.71 KB
/
mutex_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
package cmutex
import (
"context"
"github.com/stretchr/testify/assert"
"sync"
"testing"
"time"
)
func TestMutex_Lock(t *testing.T) {
ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
defer cancel()
m := NewMutex()
assert.Nil(t, m.Lock(ctx))
assert.True(t, m.Lock(ctx) != nil)
m.Unlock()
assert.Nil(t, m.Lock(context.TODO()))
}
func TestMutex_TryLock(t *testing.T) {
m := NewMutex()
assert.Nil(t, m.Lock(context.TODO()))
assert.False(t, m.TryLock())
m.Unlock()
assert.True(t, m.TryLock())
}
var (
rCount = 100
totalTime = time.Duration(rCount) * sleepTime
)
func TestLock2(t *testing.T) {
start := time.Now()
m := NewMutex()
value := 0
wg := sync.WaitGroup{}
for i := 0; i < rCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_ = m.Lock(context.TODO())
defer m.Unlock()
assert.Equal(t, value, 0)
value = 1
time.Sleep(sleepTime)
value = 0
}()
}
wg.Wait()
t.Log(time.Now().Sub(start), totalTime)
assert.True(t, time.Now().Sub(start) >= totalTime)
}
var (
cm = NewMutex()
m = sync.Mutex{}
)
func BenchmarkMutex_Lock(b *testing.B) {
for i := 0; i < b.N; i++ {
m.Lock()
m.Unlock()
}
}
func BenchmarkCMutex_Lock(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = cm.Lock(context.TODO())
cm.Unlock()
}
}
func BenchmarkMutex_Race(b *testing.B) {
for i := 0; i < b.N; i++ {
wg := sync.WaitGroup{}
for j := 0; j < 50; j++ {
wg.Add(1)
go func() {
m.Lock()
m.Unlock()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkCMutex_Race(b *testing.B) {
for i := 0; i < b.N; i++ {
wg := sync.WaitGroup{}
for j := 0; j < 50; j++ {
wg.Add(1)
go func() {
_ = cm.Lock(context.TODO())
cm.Unlock()
wg.Done()
}()
}
wg.Wait()
}
}