Skip to content

Commit

Permalink
Merge pull request hybridgroup#235 from joushou/savetheroutines
Browse files Browse the repository at this point in the history
Save ~1000 goroutines
  • Loading branch information
deadprogram committed Oct 1, 2015
2 parents cb39c33 + 4164003 commit a423687
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 28 deletions.
38 changes: 12 additions & 26 deletions event.go
Original file line number Diff line number Diff line change
@@ -1,49 +1,35 @@
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 {
Chan chan interface{}
sync.Mutex
Callbacks []callback
}

// NewEvent returns a new Event which is now listening for data.
func NewEvent() *Event {
e := &Event{
Chan: make(chan interface{}, 1),
Callbacks: []callback{},
}
go func() {
for {
e.Read()
}
}()
return e
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{}) {
select {
case e.Chan <- data:
default:
}
}
e.Lock()
defer e.Unlock()

// Read executes all Callbacks when new data is available.
func (e *Event) Read() {
for s := range e.Chan {
tmp := []callback{}
for i := range e.Callbacks {
go e.Callbacks[i].f(s)
if !e.Callbacks[i].once {
tmp = append(tmp, e.Callbacks[i])
}
tmp := []callback{}
for _, cb := range e.Callbacks {
go cb.f(data)
if !cb.once {
tmp = append(tmp, cb)
}
e.Callbacks = tmp
}
e.Callbacks = tmp
}
12 changes: 10 additions & 2 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,20 @@ func TestAfter(t *testing.T) {
}

func TestPublish(t *testing.T) {
e := &Event{Chan: make(chan interface{}, 1)}
c := make(chan interface{}, 1)

cb := callback{
f: func(val interface{}) {
c <- val
},
}

e := &Event{Callbacks: []callback{cb}}
Publish(e, 1)
Publish(e, 2)
Publish(e, 3)
Publish(e, 4)
i := <-e.Chan
i := <-c
Assert(t, i, 1)

var e1 = (*Event)(nil)
Expand Down

0 comments on commit a423687

Please sign in to comment.