Skip to content

Commit

Permalink
Optimize cycle in Acquire
Browse files Browse the repository at this point in the history
  • Loading branch information
marusama committed Jan 17, 2018
1 parent 4d8fe3d commit e66277a
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,16 @@ func (s *semaphore) Acquire(ctx context.Context, n int) error {
if n <= 0 {
panic("n must be positive number")
}
var ctxDoneCh <-chan struct{}
if ctx != nil {
ctxDoneCh = ctx.Done()
}
for {
if ctx != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// check if context is done
select {
case <-ctxDoneCh:
return ctx.Err()
default:
}

// get current semaphore count and limit
Expand All @@ -108,18 +111,12 @@ func (s *semaphore) Acquire(ctx context.Context, n int) error {
broadcastCh := s.broadcastCh
s.lock.RUnlock()

if ctx != nil {
select {
case <-ctx.Done():
return ctx.Err()
// waiting for broadcast signal
case <-broadcastCh:
}
} else {
select {
// waiting for broadcast signal
case <-broadcastCh:
}
select {
// check if context is done
case <-ctxDoneCh:
return ctx.Err()
// waiting for broadcast signal
case <-broadcastCh:
}
}
}
Expand Down

0 comments on commit e66277a

Please sign in to comment.