@@ -33,9 +33,8 @@ var errBadChannel = errors.New("event: Subscribe argument does not have sendable
33
33
//
34
34
// The zero value is ready to use.
35
35
type Feed struct {
36
- // sendLock has a one-element buffer and is empty when held.
37
- // It protects sendCases.
38
- sendLock chan struct {}
36
+ once sync.Once // ensures that init only runs once
37
+ sendLock chan struct {} // sendLock has a one-element buffer and is empty when held.It protects sendCases.
39
38
removeSub chan interface {} // interrupts Send
40
39
sendCases caseList // the active set of select cases used by Send
41
40
@@ -60,9 +59,6 @@ func (e feedTypeError) Error() string {
60
59
}
61
60
62
61
func (f * Feed ) init () {
63
- if f .sendLock != nil {
64
- return
65
- }
66
62
f .removeSub = make (chan interface {})
67
63
f .sendLock = make (chan struct {}, 1 )
68
64
f .sendLock <- struct {}{}
@@ -75,6 +71,8 @@ func (f *Feed) init() {
75
71
// The channel should have ample buffer space to avoid blocking other subscribers.
76
72
// Slow subscribers are not dropped.
77
73
func (f * Feed ) Subscribe (channel interface {}) Subscription {
74
+ f .once .Do (f .init )
75
+
78
76
chanval := reflect .ValueOf (channel )
79
77
chantyp := chanval .Type ()
80
78
if chantyp .Kind () != reflect .Chan || chantyp .ChanDir ()& reflect .SendDir == 0 {
@@ -84,7 +82,6 @@ func (f *Feed) Subscribe(channel interface{}) Subscription {
84
82
85
83
f .mu .Lock ()
86
84
defer f .mu .Unlock ()
87
- f .init ()
88
85
if ! f .typecheck (chantyp .Elem ()) {
89
86
panic (feedTypeError {op : "Subscribe" , got : chantyp , want : reflect .ChanOf (reflect .SendDir , f .etype )})
90
87
}
@@ -130,10 +127,7 @@ func (f *Feed) remove(sub *feedSub) {
130
127
// Send delivers to all subscribed channels simultaneously.
131
128
// It returns the number of subscribers that the value was sent to.
132
129
func (f * Feed ) Send (value interface {}) (nsent int ) {
133
- f .mu .Lock ()
134
- f .init ()
135
- f .mu .Unlock ()
136
-
130
+ f .once .Do (f .init )
137
131
<- f .sendLock
138
132
139
133
// Add new cases from the inbox after taking the send lock.
0 commit comments