eventer: fix data race

This commit is contained in:
Felix Lange 2014-10-08 16:26:14 +02:00
parent d451269977
commit 44674cb96c

View File

@ -1,5 +1,7 @@
package eventer package eventer
import "sync"
// Basic receiver interface. // Basic receiver interface.
type Receiver interface { type Receiver interface {
Send(Event) Send(Event)
@ -27,17 +29,18 @@ type Event struct {
type Channels map[string][]Receiver type Channels map[string][]Receiver
type EventMachine struct { type EventMachine struct {
mu sync.RWMutex
channels Channels channels Channels
} }
func New() *EventMachine { func New() *EventMachine {
return &EventMachine{ return &EventMachine{channels: make(Channels)}
channels: make(Channels),
}
} }
func (self *EventMachine) add(typ string, r Receiver) { func (self *EventMachine) add(typ string, r Receiver) {
self.mu.Lock()
self.channels[typ] = append(self.channels[typ], r) self.channels[typ] = append(self.channels[typ], r)
self.mu.Unlock()
} }
// Generalised methods for the known receiver types // Generalised methods for the known receiver types
@ -64,11 +67,11 @@ func (self *EventMachine) RegisterFunc(typ string, f Function) {
func (self *EventMachine) Register(typ string) Channel { func (self *EventMachine) Register(typ string) Channel {
c := make(Channel, 1) c := make(Channel, 1)
self.add(typ, c) self.add(typ, c)
return c return c
} }
func (self *EventMachine) Post(typ string, data interface{}) { func (self *EventMachine) Post(typ string, data interface{}) {
self.mu.RLock()
if self.channels[typ] != nil { if self.channels[typ] != nil {
ev := Event{typ, data} ev := Event{typ, data}
for _, receiver := range self.channels[typ] { for _, receiver := range self.channels[typ] {
@ -76,4 +79,5 @@ func (self *EventMachine) Post(typ string, data interface{}) {
receiver.Send(ev) receiver.Send(ev)
} }
} }
self.mu.RUnlock()
} }