Skip to content

Commit 10bbf26

Browse files
committed
event: make Unsubscribe idempotent
1 parent dac4a8f commit 10bbf26

1 file changed

Lines changed: 16 additions & 7 deletions

File tree

‎event/event.go‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -124,14 +124,16 @@ func posdelete(slice []*muxsub, pos int) []*muxsub {
124124

125125
type muxsub struct {
126126
mux *TypeMux
127-
mutex sync.RWMutex
127+
closeMu sync.Mutex
128128
closing chan struct{}
129+
closed bool
129130

130131
// these two are the same channel. they are stored separately so
131132
// postC can be set to nil without affecting the return value of
132133
// Chan.
133-
readC <-chan interface{}
134-
postC chan<- interface{}
134+
postMu sync.RWMutex
135+
readC <-chan interface{}
136+
postC chan<- interface{}
135137
}
136138

137139
func newsub(mux *TypeMux) *muxsub {
@@ -154,18 +156,25 @@ func (s *muxsub) Unsubscribe() {
154156
}
155157

156158
func (s *muxsub) closewait() {
159+
s.closeMu.Lock()
160+
defer s.closeMu.Unlock()
161+
if s.closed {
162+
return
163+
}
157164
close(s.closing)
158-
s.mutex.Lock()
165+
s.closed = true
166+
167+
s.postMu.Lock()
159168
close(s.postC)
160169
s.postC = nil
161-
s.mutex.Unlock()
170+
s.postMu.Unlock()
162171
}
163172

164173
func (s *muxsub) deliver(ev interface{}) {
165-
s.mutex.RLock()
174+
s.postMu.RLock()
166175
select {
167176
case s.postC <- ev:
168177
case <-s.closing:
169178
}
170-
s.mutex.RUnlock()
179+
s.postMu.RUnlock()
171180
}

0 commit comments

Comments
 (0)