From 499812e8021a18c25647d65825ba1c43073495e1 Mon Sep 17 00:00:00 2001 From: kpango Date: Fri, 18 Nov 2022 15:50:29 +0900 Subject: [PATCH] [patch] remove time.Local for resolving race condition Signed-off-by: kpango --- example/main.go | 5 +++++ fastime.go | 11 +++++++++-- now.go | 14 +++++++++++--- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/example/main.go b/example/main.go index 5e50cb5..d8c8f83 100644 --- a/example/main.go +++ b/example/main.go @@ -25,6 +25,11 @@ func main() { fastime.UnixNanoNow()+int64(time.Second), string(fastime.FormattedNow())) + go func(){ + time.Sleep(time.Second * 2) + fastime.SetLocation(time.FixedZone("Asia/Tokyo", 9*60*60)) + }() + for i := 0; i < 30; i++ { time.Sleep(time.Millisecond * 400) fmt.Println(fastime.Now()) diff --git a/fastime.go b/fastime.go index 5f8fa06..9fc069f 100644 --- a/fastime.go +++ b/fastime.go @@ -66,7 +66,7 @@ func newFastime() *fastime { }(), location: func() *atomic.Value { av := new(atomic.Value) - av.Store(time.Local) + av.Store(new(time.Location)) return av }(), correctionDur: time.Millisecond * 100, @@ -116,7 +116,11 @@ func (f *fastime) IsDaemonRunning() bool { } func (f *fastime) GetLocation() *time.Location { - return f.location.Load().(*time.Location) + l := f.location.Load() + if l == nil{ + return nil + } + return l.(*time.Location) } func (f *fastime) GetFormat() string { @@ -125,6 +129,9 @@ func (f *fastime) GetFormat() string { // SetLocation replaces time location func (f *fastime) SetLocation(location *time.Location) Fastime { + if location == nil{ + return f + } f.location.Store(location) f.refresh() return f diff --git a/now.go b/now.go index 3643822..53ec5d6 100644 --- a/now.go +++ b/now.go @@ -8,12 +8,20 @@ import ( "time" ) -func (f *fastime) now() time.Time { +func (f *fastime) now() (now time.Time) { var tv syscall.Timeval err := syscall.Gettimeofday(&tv) loc := f.GetLocation() if err != nil { - return time.Now().In(loc) + now = time.Now() + if loc != nil{ + return now.In(loc) + } + return now } - return time.Unix(0, syscall.TimevalToNsec(tv)).In(loc) + now = time.Unix(0, syscall.TimevalToNsec(tv)) + if loc != nil{ + return now.In(loc) + } + return now }