-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbroadcast_test.go
115 lines (98 loc) · 1.71 KB
/
broadcast_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
111
112
113
114
115
package broadcast_test
import (
"context"
"sync"
"testing"
"github.com/teivah/broadcast"
)
func TestNotify(t *testing.T) {
relay := broadcast.NewRelay[struct{}]()
list1 := relay.Listener(0)
list2 := relay.Listener(0)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
<-list1.Ch()
wg.Done()
}()
go func() {
<-list2.Ch()
wg.Done()
}()
relay.Notify(struct{}{})
wg.Wait()
wg.Add(1)
go func() {
<-list2.Ch()
wg.Done()
}()
list1.Close()
relay.Notify(struct{}{})
wg.Wait()
list2.Close()
relay.Notify(struct{}{})
list1.Close()
list2.Close()
relay.Close()
}
func TestBroadcast(t *testing.T) {
relay := broadcast.NewRelay[struct{}]()
relay.Listener(0)
relay.Broadcast(struct{}{})
relay.Close()
}
func TestNotifyCtx(t *testing.T) {
relay := broadcast.NewRelay[struct{}]()
relay.Listener(0)
ctx, cancel := context.WithCancel(context.Background())
cancel()
relay.NotifyCtx(ctx, struct{}{})
}
func TestRaceBroadcast(t *testing.T) {
relay := broadcast.NewRelay[struct{}]()
wg := sync.WaitGroup{}
funcs := []func(){
func() {
listener := relay.Listener(1)
select {
case <-listener.Ch():
default:
}
listener.Close()
},
func() {
relay.Broadcast(struct{}{})
},
}
for i := 0; i < 1000; i++ {
for _, f := range funcs {
f := f
wg.Add(1)
go func() {
f()
wg.Done()
}()
}
}
relay.Broadcast(struct{}{})
wg.Wait()
relay.Close()
}
func TestRaceClosure(t *testing.T) {
for i := 0; i < 1000; i++ {
relay := broadcast.NewRelay[struct{}]()
list := []*broadcast.Listener[struct{}]{
relay.Listener(0),
relay.Listener(0),
relay.Listener(0),
}
go func() {
relay.Close()
}()
go func() {
for _, l := range list {
l.Close()
}
}()
}
}