Skip to content

Commit

Permalink
[patch] remove time.Local for resolving race condition
Browse files Browse the repository at this point in the history
Signed-off-by: kpango <kpango@vdaas.org>
  • Loading branch information
kpango committed Nov 18, 2022
1 parent bb0c6e4 commit 499812e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
5 changes: 5 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
11 changes: 9 additions & 2 deletions fastime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down
14 changes: 11 additions & 3 deletions now.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 499812e

Please sign in to comment.