Skip to content

Commit

Permalink
Merge pull request #37 from dnozdrin/fix-time-after
Browse files Browse the repository at this point in the history
Improved memory consumption on timeout checks
  • Loading branch information
eapache authored Aug 14, 2023
2 parents 83b926b + d764524 commit b3313d8
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
7 changes: 6 additions & 1 deletion deadline/deadline.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,15 @@ func (d *Deadline) Run(work func(<-chan struct{}) error) error {
}
}()

timer := time.NewTimer(d.timeout)
select {
case ret := <-result:
if !timer.Stop() {
<-timer.C
}

return ret
case <-time.After(d.timeout):
case <-timer.C:
close(stopper)
return ErrTimedOut
}
Expand Down
12 changes: 8 additions & 4 deletions retrier/retrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ func (r *Retrier) RunCtx(ctx context.Context, work func(ctx context.Context) err
return ret
}

timeout := time.After(r.calcSleep(retries))
if err := r.sleep(ctx, timeout); err != nil {
timer := time.NewTimer(r.calcSleep(retries))
if err := r.sleep(ctx, timer); err != nil {
return err
}

Expand All @@ -70,11 +70,15 @@ func (r *Retrier) RunCtx(ctx context.Context, work func(ctx context.Context) err
}
}

func (r *Retrier) sleep(ctx context.Context, t <-chan time.Time) error {
func (r *Retrier) sleep(ctx context.Context, timer *time.Timer) error {
select {
case <-t:
case <-timer.C:
return nil
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}

return ctx.Err()
}
}
Expand Down
7 changes: 6 additions & 1 deletion semaphore/semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,15 @@ func New(tickets int, timeout time.Duration) *Semaphore {
// If it cannot after "timeout" amount of time, it returns ErrNoTickets. It is
// safe to call Acquire concurrently on a single Semaphore.
func (s *Semaphore) Acquire() error {
timer := time.NewTimer(s.timeout)
select {
case s.sem <- struct{}{}:
if !timer.Stop() {
<-timer.C
}

return nil
case <-time.After(s.timeout):
case <-timer.C:
return ErrNoTickets
}
}
Expand Down

0 comments on commit b3313d8

Please sign in to comment.