perf: use waitgroup instead of loop to wait on timers

fg-job
TorchedSammy 2022-05-21 21:58:58 -04:00
parent a4b358fd9c
commit d808534da6
Signed by: sammyette
GPG Key ID: 904FC49417B44DCD
3 changed files with 9 additions and 5 deletions

View File

@ -301,11 +301,7 @@ func exit(code int) {
// wait for all timers to finish before exiting. // wait for all timers to finish before exiting.
// only do that when not interactive // only do that when not interactive
if !interactive { if !interactive {
for { timers.wait()
if timers.running == 0 {
os.Exit(code)
}
}
} }
os.Exit(code) os.Exit(code)

View File

@ -35,6 +35,7 @@ func (t *timer) start() error {
t.running = true t.running = true
t.th.running++ t.th.running++
t.th.wg.Add(1)
t.ticker = time.NewTicker(t.dur) t.ticker = time.NewTicker(t.dur)
go func() { go func() {
@ -68,6 +69,7 @@ func (t *timer) stop() error {
t.channel <- struct{}{} t.channel <- struct{}{}
t.running = false t.running = false
t.th.running-- t.th.running--
t.th.wg.Done()
return nil return nil
} }

View File

@ -12,6 +12,7 @@ import (
var timers *timerHandler var timers *timerHandler
type timerHandler struct { type timerHandler struct {
mu *sync.RWMutex mu *sync.RWMutex
wg *sync.WaitGroup
timers map[int]*timer timers map[int]*timer
latestID int latestID int
running int running int
@ -22,9 +23,14 @@ func newTimerHandler() *timerHandler {
timers: make(map[int]*timer), timers: make(map[int]*timer),
latestID: 0, latestID: 0,
mu: &sync.RWMutex{}, mu: &sync.RWMutex{},
wg: &sync.WaitGroup{},
} }
} }
func (th *timerHandler) wait() {
th.wg.Wait()
}
func (th *timerHandler) create(typ timerType, dur time.Duration, fun *rt.Closure) *timer { func (th *timerHandler) create(typ timerType, dur time.Duration, fun *rt.Closure) *timer {
th.mu.Lock() th.mu.Lock()
defer th.mu.Unlock() defer th.mu.Unlock()