Merge pull request #1854 from calmh/eventmemallocs
Reuse a timer instead of allocating a new one in subscription.Poll
This commit is contained in:
commit
feecdcc7a4
@ -100,9 +100,10 @@ type Event struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Subscription struct {
|
type Subscription struct {
|
||||||
mask EventType
|
mask EventType
|
||||||
id int
|
id int
|
||||||
events chan Event
|
events chan Event
|
||||||
|
timeout *time.Timer
|
||||||
}
|
}
|
||||||
|
|
||||||
var Default = NewLogger()
|
var Default = NewLogger()
|
||||||
@ -149,9 +150,10 @@ func (l *Logger) Subscribe(mask EventType) *Subscription {
|
|||||||
dl.Debugln("subscribe", mask)
|
dl.Debugln("subscribe", mask)
|
||||||
}
|
}
|
||||||
s := &Subscription{
|
s := &Subscription{
|
||||||
mask: mask,
|
mask: mask,
|
||||||
id: l.nextID,
|
id: l.nextID,
|
||||||
events: make(chan Event, BufferSize),
|
events: make(chan Event, BufferSize),
|
||||||
|
timeout: time.NewTimer(0),
|
||||||
}
|
}
|
||||||
l.nextID++
|
l.nextID++
|
||||||
l.subs[s.id] = s
|
l.subs[s.id] = s
|
||||||
@ -169,19 +171,22 @@ func (l *Logger) Unsubscribe(s *Subscription) {
|
|||||||
l.mutex.Unlock()
|
l.mutex.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Poll returns an event from the subscription or an error if the poll times
|
||||||
|
// out of the event channel is closed. Poll should not be called concurrently
|
||||||
|
// from multiple goroutines for a single subscription.
|
||||||
func (s *Subscription) Poll(timeout time.Duration) (Event, error) {
|
func (s *Subscription) Poll(timeout time.Duration) (Event, error) {
|
||||||
if debug {
|
if debug {
|
||||||
dl.Debugln("poll", timeout)
|
dl.Debugln("poll", timeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
to := time.After(timeout)
|
s.timeout.Reset(timeout)
|
||||||
select {
|
select {
|
||||||
case e, ok := <-s.events:
|
case e, ok := <-s.events:
|
||||||
if !ok {
|
if !ok {
|
||||||
return e, ErrClosed
|
return e, ErrClosed
|
||||||
}
|
}
|
||||||
return e, nil
|
return e, nil
|
||||||
case <-to:
|
case <-s.timeout.C:
|
||||||
return Event{}, ErrTimeout
|
return Event{}, ErrTimeout
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user