From 1c54274ec137fe97454c043f69f2e6e960b419e7 Mon Sep 17 00:00:00 2001 From: Lyon Hill Date: Fri, 8 Nov 2019 15:08:15 -0700 Subject: [PATCH] fix: add locking around timers to avoid race add locking around access and updates to the stopped field. --- clock.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/clock.go b/clock.go index c4c5230..a48e6ac 100644 --- a/clock.go +++ b/clock.go @@ -255,8 +255,13 @@ func (t *Timer) Stop() bool { return t.timer.Stop() } + t.mock.mu.Lock() registered := !t.stopped + t.mock.mu.Unlock() + t.mock.removeClockTimer((*internalTimer)(t)) + t.mock.mu.Lock() + defer t.mock.mu.Unlock() t.stopped = true return registered } @@ -268,12 +273,14 @@ func (t *Timer) Reset(d time.Duration) bool { } t.next = t.mock.now.Add(d) + t.mock.mu.Lock() + defer t.mock.mu.Unlock() + registered := !t.stopped if t.stopped { - t.mock.mu.Lock() t.mock.timers = append(t.mock.timers, (*internalTimer)(t)) - t.mock.mu.Unlock() } + t.stopped = false return registered } @@ -288,6 +295,9 @@ func (t *internalTimer) Tick(now time.Time) { t.c <- now } t.mock.removeClockTimer((*internalTimer)(t)) + t.mock.mu.Lock() + defer t.mock.mu.Unlock() + t.stopped = true gosched() }