Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove data race when resetting ticker #161

Merged
merged 1 commit into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions externalclock/clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,37 @@ func TestExternalClock_TestLooper(t *testing.T) {
assert.Equal(t, looper.Target, looper.counter)
}

func TestTicker_ResetRace(t *testing.T) {
// This test does not have any assertions, and instead is intended to catch
// data races with `-race` flag set.
const (
ticks = 100
tickInterval = time.Millisecond
)
clock := newTestFixture(t)
done := make(chan struct{}, 2)
go func() {
initialTime := time.Unix(0, 0)
for i := 0; i < ticks; i++ {
clock.SetTimestamp(initialTime.Add(time.Second))
time.Sleep(tickInterval)
}
done <- struct{}{}
}()
go func() {
ticker := clock.NewTicker(time.Second)
for i := 0; i < ticks; i++ {
ticker.Reset(time.Second)
time.Sleep(tickInterval)
}
ticker.Stop()
done <- struct{}{}
}()

<-done
<-done
}

func TestExternalClock_TestLooper_AddTicker(t *testing.T) {
externalClock := newTestFixture(t)
ctx, cancel := context.WithCancel(context.Background())
Expand Down
10 changes: 8 additions & 2 deletions externalclock/ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ func (t *ticker) Stop() {

func (t *ticker) Reset(duration time.Duration) {
now := t.getTimeFunc()
t.mutex.Lock()
t.duration = duration
t.SetLastTimestamp(now)
t.lastTimeStamp = now
t.mutex.Unlock()
}

func (t *ticker) IsDurationReached(currentTime time.Time) bool {
return t.duration <= currentTime.Sub(t.GetLastTimestamp())
t.mutex.Lock()
dur := t.duration
ts := t.lastTimeStamp
t.mutex.Unlock()
return dur <= currentTime.Sub(ts)
}

func (t *ticker) GetLastTimestamp() time.Time {
Expand Down