woodpecker/engine/bus.go

49 lines
879 B
Go
Raw Normal View History

2015-09-30 01:21:17 +00:00
package engine
import (
"sync"
)
2015-09-30 01:21:17 +00:00
type eventbus struct {
sync.Mutex
2015-09-30 01:21:17 +00:00
subs map[chan *Event]bool
}
2015-09-30 01:21:17 +00:00
// New creates a new eventbus that manages a list of
// subscribers to which events are published.
2015-09-30 01:21:17 +00:00
func newEventbus() *eventbus {
return &eventbus{
subs: make(map[chan *Event]bool),
}
}
// Subscribe adds the channel to the list of
// subscribers. Each subscriber in the list will
// receive broadcast events.
2015-09-30 01:21:17 +00:00
func (b *eventbus) subscribe(c chan *Event) {
b.Lock()
b.subs[c] = true
b.Unlock()
}
// Unsubscribe removes the channel from the
// list of subscribers.
2015-09-30 01:21:17 +00:00
func (b *eventbus) unsubscribe(c chan *Event) {
b.Lock()
delete(b.subs, c)
b.Unlock()
}
// Send dispatches a message to all subscribers.
2015-09-30 01:21:17 +00:00
func (b *eventbus) send(event *Event) {
b.Lock()
defer b.Unlock()
2015-04-28 22:30:51 +00:00
for s := range b.subs {
2015-09-30 01:21:17 +00:00
go func(c chan *Event) {
defer recover()
c <- event
}(s)
}
}