Skip to content

Commit

Permalink
cond: improve the usage of timer (#5634)
Browse files Browse the repository at this point in the history
  • Loading branch information
SandyXSD authored Feb 8, 2025
1 parent 58cf613 commit 8e15fec
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions pkg/utils/cond.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8e15fec

Please sign in to comment.