mirror of
https://github.com/yusing/godoxy.git
synced 2026-03-21 16:49:03 +01:00
fix(time): data race in DefaultTimeNow
This commit is contained in:
@@ -10,7 +10,7 @@ var (
|
||||
TimeNow = DefaultTimeNow
|
||||
shouldCallTimeNow atomic.Bool
|
||||
timeNowTicker = time.NewTicker(shouldCallTimeNowInterval)
|
||||
lastTimeNow = time.Now()
|
||||
lastTimeNow = atomic.NewTime(time.Now())
|
||||
)
|
||||
|
||||
const shouldCallTimeNowInterval = 100 * time.Millisecond
|
||||
@@ -26,11 +26,13 @@ func MockTimeNow(t time.Time) {
|
||||
//
|
||||
// Returned value may have +-100ms error.
|
||||
func DefaultTimeNow() time.Time {
|
||||
if shouldCallTimeNow.Load() {
|
||||
lastTimeNow = time.Now()
|
||||
shouldCallTimeNow.Store(false)
|
||||
swapped := shouldCallTimeNow.CompareAndSwap(false, true)
|
||||
if swapped { // first call
|
||||
now := time.Now()
|
||||
lastTimeNow.Store(now)
|
||||
return now
|
||||
}
|
||||
return lastTimeNow
|
||||
return lastTimeNow.Load()
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -5,16 +5,18 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var sink time.Time
|
||||
|
||||
func BenchmarkTimeNow(b *testing.B) {
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
time.Now()
|
||||
sink = time.Now()
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("reduced_call", func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
DefaultTimeNow()
|
||||
sink = DefaultTimeNow()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user