Skip to content

Commit f5b8775

Browse files
committed
event: new package for event multiplexer
1 parent bb50386 commit f5b8775

2 files changed

Lines changed: 323 additions & 0 deletions

File tree

‎event/event.go‎

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
// Package event implements an event multiplexer.
2+
package event
3+
4+
import (
5+
"errors"
6+
"reflect"
7+
"sync"
8+
)
9+
10+
type Subscription interface {
11+
Chan() <-chan interface{}
12+
Unsubscribe()
13+
}
14+
15+
// A TypeMux dispatches events to registered receivers. Receivers can be
16+
// registered to handle events of certain type. Any operation
17+
// called after mux is stopped will return ErrMuxClosed.
18+
type TypeMux struct {
19+
mutex sync.RWMutex
20+
subm map[reflect.Type][]*muxsub
21+
stopped bool
22+
}
23+
24+
var ErrMuxClosed = errors.New("event: mux closed")
25+
26+
// NewTypeMux creates a running mux.
27+
func NewTypeMux() *TypeMux {
28+
return &TypeMux{subm: make(map[reflect.Type][]*muxsub)}
29+
}
30+
31+
// Subscribe creates a subscription for events of the given types. The
32+
// subscription's channel is closed when it is unsubscribed
33+
// or the mux is closed.
34+
func (mux *TypeMux) Subscribe(types ...interface{}) Subscription {
35+
sub := newsub(mux)
36+
mux.mutex.Lock()
37+
if mux.stopped {
38+
mux.mutex.Unlock()
39+
close(sub.postC)
40+
} else {
41+
for _, t := range types {
42+
rtyp := reflect.TypeOf(t)
43+
oldsubs := mux.subm[rtyp]
44+
subs := make([]*muxsub, len(oldsubs)+1)
45+
copy(subs, oldsubs)
46+
subs[len(oldsubs)] = sub
47+
mux.subm[rtyp] = subs
48+
}
49+
mux.mutex.Unlock()
50+
}
51+
return sub
52+
}
53+
54+
// Post sends an event to all receivers registered for the given type.
55+
// It returns ErrMuxClosed if the mux has been stopped.
56+
func (mux *TypeMux) Post(ev interface{}) error {
57+
rtyp := reflect.TypeOf(ev)
58+
mux.mutex.RLock()
59+
if mux.stopped {
60+
mux.mutex.RUnlock()
61+
return ErrMuxClosed
62+
}
63+
subs := mux.subm[rtyp]
64+
mux.mutex.RUnlock()
65+
for _, sub := range subs {
66+
sub.deliver(ev)
67+
}
68+
return nil
69+
}
70+
71+
// Stop closes a mux. The mux can no longer be used.
72+
// Future Post calls will fail with ErrMuxClosed.
73+
// Stop blocks until all current deliveries have finished.
74+
func (mux *TypeMux) Stop() {
75+
mux.mutex.Lock()
76+
for _, subs := range mux.subm {
77+
for _, sub := range subs {
78+
sub.closewait()
79+
}
80+
}
81+
mux.subm = nil
82+
mux.stopped = true
83+
mux.mutex.Unlock()
84+
}
85+
86+
func (mux *TypeMux) del(s *muxsub) {
87+
mux.mutex.Lock()
88+
for typ, subs := range mux.subm {
89+
if pos := find(subs, s); pos >= 0 {
90+
if len(subs) == 1 {
91+
delete(mux.subm, typ)
92+
} else {
93+
mux.subm[typ] = posdelete(subs, pos)
94+
}
95+
}
96+
}
97+
s.mux.mutex.Unlock()
98+
}
99+
100+
func find(slice []*muxsub, item *muxsub) int {
101+
for i, v := range slice {
102+
if v == item {
103+
return i
104+
}
105+
}
106+
return -1
107+
}
108+
109+
func posdelete(slice []*muxsub, pos int) []*muxsub {
110+
news := make([]*muxsub, len(slice)-1)
111+
copy(news[:pos], slice[:pos])
112+
copy(news[pos:], slice[pos+1:])
113+
return news
114+
}
115+
116+
type muxsub struct {
117+
mux *TypeMux
118+
mutex sync.RWMutex
119+
closing chan struct{}
120+
121+
// these two are the same channel. they are stored separately so
122+
// postC can be set to nil without affecting the return value of
123+
// Chan.
124+
readC <-chan interface{}
125+
postC chan<- interface{}
126+
}
127+
128+
func newsub(mux *TypeMux) *muxsub {
129+
c := make(chan interface{})
130+
return &muxsub{
131+
mux: mux,
132+
readC: c,
133+
postC: c,
134+
closing: make(chan struct{}),
135+
}
136+
}
137+
138+
func (s *muxsub) Chan() <-chan interface{} {
139+
return s.readC
140+
}
141+
142+
func (s *muxsub) Unsubscribe() {
143+
s.mux.del(s)
144+
s.closewait()
145+
}
146+
147+
func (s *muxsub) closewait() {
148+
close(s.closing)
149+
s.mutex.Lock()
150+
close(s.postC)
151+
s.postC = nil
152+
s.mutex.Unlock()
153+
}
154+
155+
func (s *muxsub) deliver(ev interface{}) {
156+
s.mutex.RLock()
157+
select {
158+
case s.postC <- ev:
159+
case <-s.closing:
160+
}
161+
s.mutex.RUnlock()
162+
}

‎event/event_test.go‎

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
package event
2+
3+
import (
4+
"math/rand"
5+
"sync"
6+
"testing"
7+
"time"
8+
)
9+
10+
type testEvent int
11+
12+
func TestSub(t *testing.T) {
13+
mux := NewTypeMux()
14+
defer mux.Stop()
15+
16+
sub := mux.Subscribe(testEvent(0))
17+
go func() {
18+
if err := mux.Post(testEvent(5)); err != nil {
19+
t.Errorf("Post returned unexpected error: %v", err)
20+
}
21+
}()
22+
ev := <-sub.Chan()
23+
24+
if ev.(testEvent) != testEvent(5) {
25+
t.Errorf("Got %v (%T), expected event %v (%T)",
26+
ev, ev, testEvent(5), testEvent(5))
27+
}
28+
}
29+
30+
func TestMuxErrorAfterStop(t *testing.T) {
31+
mux := NewTypeMux()
32+
mux.Stop()
33+
34+
sub := mux.Subscribe(testEvent(0))
35+
if _, isopen := <-sub.Chan(); isopen {
36+
t.Errorf("subscription channel was not closed")
37+
}
38+
if err := mux.Post(testEvent(0)); err != ErrMuxClosed {
39+
t.Errorf("Post error mismatch, got: %s, expected: %s", err, ErrMuxClosed)
40+
}
41+
}
42+
43+
func TestUnsubscribeUnblockPost(t *testing.T) {
44+
mux := NewTypeMux()
45+
defer mux.Stop()
46+
47+
sub := mux.Subscribe(testEvent(0))
48+
unblocked := make(chan bool)
49+
go func() {
50+
mux.Post(testEvent(5))
51+
unblocked <- true
52+
}()
53+
54+
select {
55+
case <-unblocked:
56+
t.Errorf("Post returned before Unsubscribe")
57+
default:
58+
sub.Unsubscribe()
59+
<-unblocked
60+
}
61+
}
62+
63+
func TestMuxConcurrent(t *testing.T) {
64+
rand.Seed(time.Now().Unix())
65+
mux := NewTypeMux()
66+
defer mux.Stop()
67+
68+
recv := make(chan int)
69+
poster := func() {
70+
for {
71+
err := mux.Post(testEvent(0))
72+
if err != nil {
73+
return
74+
}
75+
}
76+
}
77+
sub := func(i int) {
78+
time.Sleep(time.Duration(rand.Intn(99)) * time.Millisecond)
79+
sub := mux.Subscribe(testEvent(0))
80+
<-sub.Chan()
81+
sub.Unsubscribe()
82+
recv <- i
83+
}
84+
85+
go poster()
86+
go poster()
87+
go poster()
88+
nsubs := 1000
89+
for i := 0; i < nsubs; i++ {
90+
go sub(i)
91+
}
92+
93+
// wait until everyone has been served
94+
counts := make(map[int]int, nsubs)
95+
for i := 0; i < nsubs; i++ {
96+
counts[<-recv]++
97+
}
98+
for i, count := range counts {
99+
if count != 1 {
100+
t.Errorf("receiver %d called %d times, expected only 1 call", i, count)
101+
}
102+
}
103+
}
104+
105+
func emptySubscriber(mux *TypeMux, types ...interface{}) {
106+
s := mux.Subscribe(testEvent(0))
107+
go func() {
108+
for _ = range s.Chan() {
109+
}
110+
}()
111+
}
112+
113+
func BenchmarkPost3(b *testing.B) {
114+
var mux = NewTypeMux()
115+
defer mux.Stop()
116+
emptySubscriber(mux, testEvent(0))
117+
emptySubscriber(mux, testEvent(0))
118+
emptySubscriber(mux, testEvent(0))
119+
120+
for i := 0; i < b.N; i++ {
121+
mux.Post(testEvent(0))
122+
}
123+
}
124+
125+
func BenchmarkPostConcurrent(b *testing.B) {
126+
var mux = NewTypeMux()
127+
defer mux.Stop()
128+
emptySubscriber(mux, testEvent(0))
129+
emptySubscriber(mux, testEvent(0))
130+
emptySubscriber(mux, testEvent(0))
131+
132+
var wg sync.WaitGroup
133+
poster := func() {
134+
for i := 0; i < b.N; i++ {
135+
mux.Post(testEvent(0))
136+
}
137+
wg.Done()
138+
}
139+
wg.Add(5)
140+
for i := 0; i < 5; i++ {
141+
go poster()
142+
}
143+
wg.Wait()
144+
}
145+
146+
// for comparison
147+
func BenchmarkChanSend(b *testing.B) {
148+
c := make(chan interface{})
149+
closed := make(chan struct{})
150+
go func() {
151+
for _ = range c {
152+
}
153+
}()
154+
155+
for i := 0; i < b.N; i++ {
156+
select {
157+
case c <- i:
158+
case <-closed:
159+
}
160+
}
161+
}

0 commit comments

Comments
 (0)