-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority_mutex_test.go
104 lines (93 loc) · 1.94 KB
/
priority_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
104
package prioritymutex
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
)
func priority(ctx context.Context, p *PriorityMutex, lockFlag chan struct{}) {
p.PLock()
defer p.PUnlock()
lockFlag <- struct{}{}
<-ctx.Done()
}
var flag int32
func normal(p *PriorityMutex, lockFlag chan struct{}) {
p.Lock()
defer p.Unlock()
atomic.AddInt32(&flag, 1)
lockFlag <- struct{}{}
}
func TestPriorityMutex(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
p := &PriorityMutex{}
pLockFlag := make(chan struct{}, 1)
go priority(ctx, p, pLockFlag)
<-pLockFlag
lockFlag := make(chan struct{}, 1)
go normal(p, lockFlag)
timeOutCtx, timeCancel := context.WithTimeout(context.TODO(), time.Second)
defer timeCancel()
select {
case <-lockFlag:
t.Fatal("unreachable")
case <-timeOutCtx.Done():
}
if atomic.LoadInt32(&flag) != 0 {
t.Fatal("flag change,it should be block and not change")
}
cancel()
time.Sleep(time.Second)
<-lockFlag
if atomic.LoadInt32(&flag) != 1 {
t.Fatal("flag not change")
}
}
func TestPriority(t *testing.T) {
p := &PriorityMutex{}
sigchan := make(chan struct{})
var counter int64
doneChan := make(chan struct{}, 1)
go func(pm *PriorityMutex) {
<-sigchan
pm.Lock()
defer pm.Unlock()
t.Log(atomic.LoadInt64(&counter))
doneChan <- struct{}{}
}(p)
for i := 0; i < 1000; i++ {
go func(pm *PriorityMutex) {
<-sigchan
pm.PLock()
defer pm.PUnlock()
atomic.AddInt64(&counter, 1)
}(p)
}
close(sigchan)
<-doneChan
}
func TestSyncMutex(t *testing.T) {
p := &sync.Mutex{}
sigchan := make(chan struct{})
var counter int64
doneChan := make(chan struct{}, 1)
go func(pm *sync.Mutex) {
<-sigchan
pm.Lock()
defer pm.Unlock()
t.Log(atomic.LoadInt64(&counter))
doneChan <- struct{}{}
}(p)
for i := 0; i < 1000; i++ {
go func(pm *sync.Mutex) {
<-sigchan
pm.Lock()
defer pm.Unlock()
atomic.AddInt64(&counter, 1)
}(p)
}
close(sigchan)
<-doneChan
}