Skip to content

Commit

Permalink
Avoid memory leaks in semaphore
Browse files Browse the repository at this point in the history
  • Loading branch information
dnozdrin committed Aug 9, 2023
1 parent f5d2ae0 commit 7756df1
Showing 1 changed file with 6 additions and 1 deletion.
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 7756df1

Please sign in to comment.