From 8e15fec839ed5afbeeb07c731c11a35e17282c6f Mon Sep 17 00:00:00 2001 From: Sandy Xu Date: Sat, 8 Feb 2025 22:03:07 +0800 Subject: [PATCH] cond: improve the usage of timer (#5634) --- pkg/utils/cond.go | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/pkg/utils/cond.go b/pkg/utils/cond.go index 0869e9fb2739..1d23a6fb3d28 100644 --- a/pkg/utils/cond.go +++ b/pkg/utils/cond.go @@ -43,32 +43,29 @@ func (c *Cond) Broadcast() { c.signal = make(chan struct{}) } -var timerPool = sync.Pool{ - New: func() interface{} { - t := time.NewTimer(time.Minute) - if !t.Stop() { - <-t.C - } - return t - }, -} +var timerPool = sync.Pool{} // WaitWithTimeout wait for a signal or a period of timeout eclipsed. // returns true in case of timeout else false -func (c *Cond) WaitWithTimeout(d time.Duration) (timeout bool) { +func (c *Cond) WaitWithTimeout(d time.Duration) bool { ch := c.signal c.L.Unlock() - t := timerPool.Get().(*time.Timer) - t.Reset(d) + var t *time.Timer + if e := timerPool.Get(); e == nil { + t = time.NewTimer(d) + } else { + t = e.(*time.Timer) + t.Reset(d) + } defer func() { - if !t.Stop() && !timeout { - <-t.C - } timerPool.Put(t) c.L.Lock() }() select { case <-ch: + if !t.Stop() { + <-t.C + } return false case <-t.C: return true