Fix: singledo panic

This commit is contained in:
Dreamacro 2019-12-10 16:26:15 +08:00
parent 2334bafe68
commit 36716ca695
2 changed files with 7 additions and 5 deletions

View file

@ -13,8 +13,8 @@ type call struct {
type Single struct { type Single struct {
mux sync.Mutex mux sync.Mutex
last int64 last time.Time
wait int64 wait time.Duration
call *call call *call
result *Result result *Result
} }
@ -26,8 +26,8 @@ type Result struct {
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) { func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
s.mux.Lock() s.mux.Lock()
now := time.Now().Unix() now := time.Now()
if now < s.last+s.wait { if now.Before(s.last.Add(s.wait)) {
s.mux.Unlock() s.mux.Unlock()
return s.result.Val, s.result.Err, true 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.call = call
s.mux.Unlock() s.mux.Unlock()
call.val, call.err = fn() call.val, call.err = fn()
call.wg.Done()
s.call = nil s.call = nil
s.result = &Result{call.val, call.err} s.result = &Result{call.val, call.err}
s.last = now 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 { func NewSingle(wait time.Duration) *Single {
return &Single{wait: int64(wait)} return &Single{wait: wait}
} }

View file

@ -14,6 +14,7 @@ func TestBasic(t *testing.T) {
shardCount := 0 shardCount := 0
call := func() (interface{}, error) { call := func() (interface{}, error) {
foo++ foo++
time.Sleep(time.Millisecond * 5)
return nil, nil return nil, nil
} }