Skip to content

Commit

Permalink
Fix data race
Browse files Browse the repository at this point in the history
gaby committed Dec 16, 2024
1 parent 854a3e3 commit f887276
Showing 2 changed files with 8 additions and 12 deletions.
14 changes: 7 additions & 7 deletions time.go
Original file line number Diff line number Diff line change
@@ -24,26 +24,26 @@ func StartTimeStampUpdater() {
timestampTimer.Do(func() {
atomic.StoreUint32(&timestamp, uint32(time.Now().Unix()))

stopChan = make(chan struct{})
go func(sleep time.Duration) {
c := make(chan struct{})
stopChan = c

go func(localChan chan struct{}, sleep time.Duration) {
ticker := time.NewTicker(sleep)
defer ticker.Stop()

for {
select {
case t := <-ticker.C:
atomic.StoreUint32(&timestamp, uint32(t.Unix()))
case <-stopChan:
// Stop signal received, break the loop and exit goroutine
case <-localChan:
return
}
}
}(1 * time.Second) // duration
}(c, 1*time.Second)
})
}

// StopTimeStampUpdater stops the currently running timestamp updater goroutine.
// This prevents leaking a goroutine if the updater is no longer needed.
// StopTimeStampUpdater stops the timestamp updater
func StopTimeStampUpdater() {
if stopChan != nil {
close(stopChan)
6 changes: 1 addition & 5 deletions time_test.go
Original file line number Diff line number Diff line change
@@ -14,8 +14,6 @@ func checkTimeStamp(tb testing.TB, expectedCurrent, actualCurrent uint32) {
}

func Test_TimeStampUpdater(t *testing.T) {
t.Parallel()

StartTimeStampUpdater()

now := uint32(time.Now().Unix())
@@ -31,8 +29,6 @@ func Test_TimeStampUpdater(t *testing.T) {
}

func Test_StopTimeStampUpdater(t *testing.T) {
t.Parallel()

// Start the timestamp updater
StartTimeStampUpdater()

@@ -50,7 +46,7 @@ func Test_StopTimeStampUpdater(t *testing.T) {
stoppedTime := Timestamp()

// Wait again to see if it updates
time.Sleep(2 * time.Second)
time.Sleep(3 * time.Second)

// It should not have changed since we've stopped the updater
require.Equal(t, stoppedTime, Timestamp(), "timestamp should not change after stopping updater")

0 comments on commit f887276

Please sign in to comment.