fix race condition in repeat_timer

This commit is contained in:
Ethan Buchman
2016-06-21 14:35:00 -04:00
parent dcfa46af13
commit 3dabf304a1

View File

@ -15,6 +15,7 @@ type RepeatTimer struct {
name string name string
ticker *time.Ticker ticker *time.Ticker
quit chan struct{} quit chan struct{}
done chan struct{}
dur time.Duration dur time.Duration
} }
@ -23,6 +24,7 @@ func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
Ch: make(chan time.Time), Ch: make(chan time.Time),
ticker: time.NewTicker(dur), ticker: time.NewTicker(dur),
quit: make(chan struct{}), quit: make(chan struct{}),
done: make(chan struct{}),
name: name, name: name,
dur: dur, dur: dur,
} }
@ -36,6 +38,8 @@ func (t *RepeatTimer) fireRoutine(ticker *time.Ticker) {
case t_ := <-ticker.C: case t_ := <-ticker.C:
t.Ch <- t_ t.Ch <- t_
case <-t.quit: case <-t.quit:
// needed so we know when we can reset t.quit
t.done <- struct{}{}
return return
} }
} }
@ -64,9 +68,10 @@ func (t *RepeatTimer) Stop() bool {
exists := t.ticker != nil exists := t.ticker != nil
if exists { if exists {
t.ticker.Stop() t.ticker.Stop() // does not close the channel
t.ticker = nil
close(t.quit) close(t.quit)
<-t.done
t.ticker = nil
} }
return exists return exists
} }