-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex_test.go
110 lines (75 loc) · 1.8 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
104
105
106
107
108
109
110
package coro_test
import (
"context"
"testing"
"time"
chrono "github.com/nnikolash/go-chrono"
"github.com/nnikolash/go-coro"
"github.com/stretchr/testify/require"
)
func TestMutex_Basic1(t *testing.T) {
t.Parallel()
clock := chrono.NewSimulator(time.Unix(1, 0))
loop := coro.NewEventLoop(clock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := coro.NewMutex()
res := []int{}
loop.AddTask(func(ctx coro.Context) {
m.Lock(ctx)
defer m.Unlock()
ctx.Sleep(100 * time.Millisecond)
res = append(res, 1)
ctx.Sleep(100 * time.Millisecond)
})
loop.AddTask(func(ctx coro.Context) {
ctx.Sleep(250 * time.Millisecond)
m.Lock(ctx)
defer m.Unlock()
res = append(res, 2)
})
loop.AddTask(func(ctx coro.Context) {
ctx.Sleep(275 * time.Millisecond)
m.Lock(ctx)
defer m.Unlock()
res = append(res, 3)
})
loop.AddTask(func(ctx coro.Context) {
ctx.Sleep(300 * time.Millisecond)
m.Lock(ctx)
defer m.Unlock()
res = append(res, 4)
})
loop.AddTask(func(ctx coro.Context) {
ctx.Sleep(450 * time.Millisecond)
m.Lock(ctx)
defer m.Unlock()
res = append(res, 5)
})
clock.ProcessAll(ctx)
require.Equal(t, []int{1, 2, 3, 4, 5}, res)
}
func TestMutex_Basic2(t *testing.T) {
t.Parallel()
clock := chrono.NewSimulator(time.Unix(1, 0))
loop := coro.NewEventLoop(clock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
m := coro.NewMutex()
res := []int{}
loop.AddTask(func(ctx coro.Context) {
m.Lock(ctx)
defer m.Unlock()
ctx.Sleep(100 * time.Millisecond)
res = append(res, 1)
ctx.Sleep(100 * time.Millisecond)
})
loop.AddTask(func(ctx coro.Context) {
ctx.Sleep(10 * time.Millisecond)
m.Lock(ctx)
defer m.Unlock()
res = append(res, 2)
})
clock.ProcessAll(ctx)
require.Equal(t, []int{1, 2}, res)
}