-
Notifications
You must be signed in to change notification settings - Fork 4
/
broadcast.go
106 lines (98 loc) · 2.42 KB
/
broadcast.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
// Package broadcast implements multi-listener broadcast channels.
//
// To create an unbuffered broadcast channel, just declare a Broadcaster:
//
// var b broadcaster.Broadcaster
//
// To create a buffered broadcast channel with capacity n, call New:
//
// b := broadcaster.New(n)
//
// To add a listener to a channel, call Listen and read from Ch:
//
// l := b.Listen()
// for v := range l.Ch {
// // ...
// }
//
//
// To send to the channel, call Send:
//
// b.Send("Hello world!")
// v <- l.Ch // returns interface{}("Hello world!")
//
// To remove a listener, call Close.
//
// l.Close()
//
// To close the broadcast channel, call Close. Any existing or future listeners
// will read from a closed channel:
//
// b.Close()
// v, ok <- l.Ch // returns ok == false
package broadcast
import "sync"
// Broadcaster implements a broadcast channel.
// The zero value is a usable unbuffered channel.
type Broadcaster struct {
m sync.Mutex
listeners map[int]chan<- interface{} // lazy init
nextId int
capacity int
closed bool
}
// New returns a new Broadcaster with the given capacity (0 means unbuffered).
func New(n int) *Broadcaster {
return &Broadcaster{capacity: n}
}
// Listener implements a listening endpoint for a broadcast channel.
type Listener struct {
// Ch receives the broadcast messages.
Ch <-chan interface{}
b *Broadcaster
id int
}
// Send broadcasts a message to the channel.
// Sending on a closed channel causes a runtime panic.
func (b *Broadcaster) Send(v interface{}) {
b.m.Lock()
defer b.m.Unlock()
if b.closed {
panic("broadcast: send after close")
}
for _, l := range b.listeners {
l <- v
}
}
// Close closes the channel, disabling the sending of further messages.
func (b *Broadcaster) Close() {
b.m.Lock()
defer b.m.Unlock()
b.closed = true
for _, l := range b.listeners {
close(l)
}
}
// Listen returns a Listener for the broadcast channel.
func (b *Broadcaster) Listen() *Listener {
b.m.Lock()
defer b.m.Unlock()
if b.listeners == nil {
b.listeners = make(map[int]chan<- interface{})
}
for b.listeners[b.nextId] != nil {
b.nextId++
}
ch := make(chan interface{}, b.capacity)
if b.closed {
close(ch)
}
b.listeners[b.nextId] = ch
return &Listener{ch, b, b.nextId}
}
// Close closes the Listener, disabling the receival of further messages.
func (l *Listener) Close() {
l.b.m.Lock()
defer l.b.m.Unlock()
delete(l.b.listeners, l.id)
}