1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-26 13:48:49 +08:00
Kenny Levinsen 4164003de1 Save ~1000 goroutines
Previous code spawns ~1000 go-routines due to NewEvent. Removing a
goroutine and making the loop of callbacks happen directly in Write with
a lock reduces this to ~12 in my test.
2015-09-30 21:45:54 +02:00

36 lines
659 B
Go

package gobot
import "sync"
type callback struct {
f func(interface{})
once bool
}
// Event executes the list of Callbacks when Chan is written to.
type Event struct {
sync.Mutex
Callbacks []callback
}
// NewEvent returns a new Event which is now listening for data.
func NewEvent() *Event {
return &Event{}
}
// Write writes data to the Event, it will not block and will not buffer if there
// are no active subscribers to the Event.
func (e *Event) Write(data interface{}) {
e.Lock()
defer e.Unlock()
tmp := []callback{}
for _, cb := range e.Callbacks {
go cb.f(data)
if !cb.once {
tmp = append(tmp, cb)
}
}
e.Callbacks = tmp
}