Merge pull request #95 from tendermint/feature/repeat-timer

Refactor repeat timer
This commit is contained in:
Anton Kaliaev 2017-12-08 11:31:27 -06:00 committed by GitHub
commit b49bce2bc3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 92 additions and 72 deletions

View File

@ -1,7 +1,6 @@
package common package common
import ( import (
"sync"
"time" "time"
) )
@ -11,76 +10,93 @@ It's good for keeping connections alive.
A RepeatTimer must be Stop()'d or it will keep a goroutine alive. A RepeatTimer must be Stop()'d or it will keep a goroutine alive.
*/ */
type RepeatTimer struct { type RepeatTimer struct {
Ch chan time.Time Name string
Ch <-chan time.Time
output chan<- time.Time
input chan repeatCommand
mtx sync.Mutex dur time.Duration
name string ticker *time.Ticker
ticker *time.Ticker stopped bool
quit chan struct{}
wg *sync.WaitGroup
dur time.Duration
} }
type repeatCommand int8
const (
Reset repeatCommand = iota
RQuit
)
func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer { func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
c := make(chan time.Time)
var t = &RepeatTimer{ var t = &RepeatTimer{
Ch: make(chan time.Time), Name: name,
ticker: time.NewTicker(dur), Ch: c,
quit: make(chan struct{}), output: c,
wg: new(sync.WaitGroup), input: make(chan repeatCommand),
name: name,
dur: dur,
}
t.wg.Add(1)
go t.fireRoutine(t.ticker)
return t
}
func (t *RepeatTimer) fireRoutine(ticker *time.Ticker) { dur: dur,
for { ticker: time.NewTicker(dur),
select {
case t_ := <-ticker.C:
t.Ch <- t_
case <-t.quit:
// needed so we know when we can reset t.quit
t.wg.Done()
return
}
} }
go t.run()
return t
} }
// Wait the duration again before firing. // Wait the duration again before firing.
func (t *RepeatTimer) Reset() { func (t *RepeatTimer) Reset() {
t.Stop() t.input <- Reset
t.mtx.Lock() // Lock
defer t.mtx.Unlock()
t.ticker = time.NewTicker(t.dur)
t.quit = make(chan struct{})
t.wg.Add(1)
go t.fireRoutine(t.ticker)
} }
// For ease of .Stop()'ing services before .Start()'ing them, // For ease of .Stop()'ing services before .Start()'ing them,
// we ignore .Stop()'s on nil RepeatTimers. // we ignore .Stop()'s on nil RepeatTimers.
func (t *RepeatTimer) Stop() bool { func (t *RepeatTimer) Stop() bool {
if t == nil { // use t.stopped to gracefully handle many Stop() without blocking
if t == nil || t.stopped {
return false return false
} }
t.mtx.Lock() // Lock t.input <- RQuit
defer t.mtx.Unlock() t.stopped = true
return true
exists := t.ticker != nil }
if exists {
t.ticker.Stop() // does not close the channel func (t *RepeatTimer) run() {
select { done := false
case <-t.Ch: for !done {
// read off channel if there's anything there select {
default: case cmd := <-t.input:
} // stop goroutine if the input says so
close(t.quit) // don't close channels, as closed channels mess up select reads
t.wg.Wait() // must wait for quit to close else we race Reset done = t.processInput(cmd)
t.ticker = nil case tick := <-t.ticker.C:
} t.send(tick)
return exists }
}
}
// send performs blocking send on t.Ch
func (t *RepeatTimer) send(tick time.Time) {
// XXX: possibly it is better to not block:
// https://golang.org/src/time/sleep.go#L132
// select {
// case t.output <- tick:
// default:
// }
t.output <- tick
}
// all modifications of the internal state of ThrottleTimer
// happen in this method. It is only called from the run goroutine
// so we avoid any race conditions
func (t *RepeatTimer) processInput(cmd repeatCommand) (shutdown bool) {
switch cmd {
case Reset:
t.ticker.Stop()
t.ticker = time.NewTicker(t.dur)
case RQuit:
t.ticker.Stop()
shutdown = true
default:
panic("unknown command!")
}
return shutdown
} }

View File

@ -10,7 +10,7 @@ import (
) )
type rCounter struct { type rCounter struct {
input chan time.Time input <-chan time.Time
mtx sync.Mutex mtx sync.Mutex
count int count int
} }
@ -39,11 +39,11 @@ func (c *rCounter) Read() {
func TestRepeat(test *testing.T) { func TestRepeat(test *testing.T) {
assert := asrt.New(test) assert := asrt.New(test)
dur := time.Duration(50) * time.Millisecond dur := time.Duration(100) * time.Millisecond
short := time.Duration(20) * time.Millisecond short := time.Duration(20) * time.Millisecond
// delay waits for cnt durations, an a little extra // delay waits for cnt durations, an a little extra
delay := func(cnt int) time.Duration { delay := func(cnt int) time.Duration {
return time.Duration(cnt)*dur + time.Duration(5)*time.Millisecond return time.Duration(cnt)*dur + time.Duration(10)*time.Millisecond
} }
t := NewRepeatTimer("bar", dur) t := NewRepeatTimer("bar", dur)
@ -70,9 +70,9 @@ func TestRepeat(test *testing.T) {
// after a stop, nothing more is sent // after a stop, nothing more is sent
stopped := t.Stop() stopped := t.Stop()
assert.True(stopped) assert.True(stopped)
time.Sleep(delay(7)) time.Sleep(delay(2))
assert.Equal(6, c.Count()) assert.Equal(6, c.Count())
// close channel to stop counter // extra calls to stop don't block
close(t.Ch) t.Stop()
} }

View File

@ -13,20 +13,21 @@ at most once every "dur".
type ThrottleTimer struct { type ThrottleTimer struct {
Name string Name string
Ch <-chan struct{} Ch <-chan struct{}
input chan command input chan throttleCommand
output chan<- struct{} output chan<- struct{}
dur time.Duration dur time.Duration
timer *time.Timer timer *time.Timer
isSet bool isSet bool
stopped bool
} }
type command int32 type throttleCommand int8
const ( const (
Set command = iota Set throttleCommand = iota
Unset Unset
Quit TQuit
) )
// NewThrottleTimer creates a new ThrottleTimer. // NewThrottleTimer creates a new ThrottleTimer.
@ -36,7 +37,7 @@ func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer {
Name: name, Name: name,
Ch: c, Ch: c,
dur: dur, dur: dur,
input: make(chan command), input: make(chan throttleCommand),
output: c, output: c,
timer: time.NewTimer(dur), timer: time.NewTimer(dur),
} }
@ -74,14 +75,14 @@ func (t *ThrottleTimer) trySend() {
// all modifications of the internal state of ThrottleTimer // all modifications of the internal state of ThrottleTimer
// happen in this method. It is only called from the run goroutine // happen in this method. It is only called from the run goroutine
// so we avoid any race conditions // so we avoid any race conditions
func (t *ThrottleTimer) processInput(cmd command) (shutdown bool) { func (t *ThrottleTimer) processInput(cmd throttleCommand) (shutdown bool) {
switch cmd { switch cmd {
case Set: case Set:
if !t.isSet { if !t.isSet {
t.isSet = true t.isSet = true
t.timer.Reset(t.dur) t.timer.Reset(t.dur)
} }
case Quit: case TQuit:
shutdown = true shutdown = true
fallthrough fallthrough
case Unset: case Unset:
@ -119,9 +120,10 @@ func (t *ThrottleTimer) Unset() {
// For ease of stopping services before starting them, we ignore Stop on nil // For ease of stopping services before starting them, we ignore Stop on nil
// ThrottleTimers. // ThrottleTimers.
func (t *ThrottleTimer) Stop() bool { func (t *ThrottleTimer) Stop() bool {
if t == nil { if t == nil || t.stopped {
return false return false
} }
t.input <- Quit t.input <- TQuit
t.stopped = true
return true return true
} }

View File

@ -95,4 +95,6 @@ func TestThrottle(test *testing.T) {
stopped := t.Stop() stopped := t.Stop()
assert.True(stopped) assert.True(stopped)
// extra calls to stop don't block
t.Stop()
} }