-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadcast_instance.go
67 lines (59 loc) · 1.36 KB
/
broadcast_instance.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
package broadcast
import (
"context"
"reflect"
)
type broadcasterInstance struct {
listenc chan chan (chan message)
listenerStubs *chanStubList
Sendc chan<- payload
}
func newInstance() *broadcasterInstance {
listenc := make(chan (chan (chan message)))
sendc := make(chan payload)
go runNotifierSafe(sendc, listenc)
return &broadcasterInstance{
listenc: listenc,
Sendc: sendc,
listenerStubs: newChanStubList(),
}
}
func (b *broadcasterInstance) AddListener(fn reflect.Value) ListenerStub {
c := make(chan chan message)
b.listenc <- c
rc := <-c
stub := newChanStub()
b.listenerStubs.Append(stub)
go runListenerSafe(rc, stub, fn)
return stub
}
func (b *broadcasterInstance) Send(ctx context.Context, v interface{}) {
b.Sendc <- newPayload(ctx, v)
}
func (b *broadcasterInstance) Stop() {
close(b.Sendc)
b.listenerStubs.Wait()
}
func runNotifierSafe(sendc chan payload, listenc chan chan chan message) {
allowPanic("broadcast.notifier", func() {
runNotifierLoop(sendc, listenc)
})
}
func runNotifierLoop(sendc chan payload, listenc chan chan chan message) {
currc := make(chan message, 1)
for {
select {
case v, ok := <-sendc:
if !ok {
currc <- terminationMsg
return
}
c := make(chan message, 1)
b := message{Next: c, Payload: v}
currc <- b
currc = c
case r := <-listenc:
r <- currc
}
}
}