From 36716ca695b2c34fa584e1ea7129a1522097fcb9 Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Tue, 10 Dec 2019 16:26:15 +0800 Subject: [PATCH] Fix: singledo panic --- common/singledo/singledo.go | 11 ++++++----- common/singledo/singledo_test.go | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/common/singledo/singledo.go b/common/singledo/singledo.go index 4828d55..8497811 100644 --- a/common/singledo/singledo.go +++ b/common/singledo/singledo.go @@ -13,8 +13,8 @@ type call struct { type Single struct { mux sync.Mutex - last int64 - wait int64 + last time.Time + wait time.Duration call *call result *Result } @@ -26,8 +26,8 @@ type Result struct { func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) { s.mux.Lock() - now := time.Now().Unix() - if now < s.last+s.wait { + now := time.Now() + if now.Before(s.last.Add(s.wait)) { s.mux.Unlock() return s.result.Val, s.result.Err, true } @@ -43,6 +43,7 @@ func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, s s.call = call s.mux.Unlock() call.val, call.err = fn() + call.wg.Done() s.call = nil s.result = &Result{call.val, call.err} s.last = now @@ -50,5 +51,5 @@ func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, s } func NewSingle(wait time.Duration) *Single { - return &Single{wait: int64(wait)} + return &Single{wait: wait} } diff --git a/common/singledo/singledo_test.go b/common/singledo/singledo_test.go index d655258..c1e48ca 100644 --- a/common/singledo/singledo_test.go +++ b/common/singledo/singledo_test.go @@ -14,6 +14,7 @@ func TestBasic(t *testing.T) { shardCount := 0 call := func() (interface{}, error) { foo++ + time.Sleep(time.Millisecond * 5) return nil, nil }