| 1 |
// Package semaphore implements the semaphore resiliency pattern for Go. |
| 2 |
package semaphore |
| 3 |
|
| 4 |
import ( |
| 5 |
"errors" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
// ErrNoTickets is the error returned by Acquire when it could not acquire |
| 10 |
// a ticket from the semaphore within the configured timeout. |
| 11 |
var ErrNoTickets = errors.New("could not acquire semaphore ticket") |
| 12 |
|
| 13 |
// Semaphore implements the semaphore resiliency pattern |
| 14 |
type Semaphore struct { |
| 15 |
sem chan struct{} |
| 16 |
timeout time.Duration |
| 17 |
} |
| 18 |
|
| 19 |
// New constructs a new Semaphore with the given ticket-count |
| 20 |
// and timeout. |
| 21 |
func New(tickets int, timeout time.Duration) *Semaphore { |
| 22 |
return &Semaphore{ |
| 23 |
sem: make(chan struct{}, tickets), |
| 24 |
timeout: timeout, |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
// Acquire tries to acquire a ticket from the semaphore. If it can, it returns nil. |
| 29 |
// If it cannot after "timeout" amount of time, it returns ErrNoTickets. It is |
| 30 |
// safe to call Acquire concurrently on a single Semaphore. |
| 31 |
func (s *Semaphore) Acquire() error { |
| 32 |
timer := time.NewTimer(s.timeout) |
| 33 |
select { |
| 34 |
case s.sem <- struct{}{}: |
| 35 |
timer.Stop() |
| 36 |
return nil |
| 37 |
case <-timer.C: |
| 38 |
return ErrNoTickets |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
// Release releases an acquired ticket back to the semaphore. It is safe to call |
| 43 |
// Release concurrently on a single Semaphore. It is an error to call Release on |
| 44 |
// a Semaphore from which you have not first acquired a ticket. |
| 45 |
func (s *Semaphore) Release() { |
| 46 |
<-s.sem |
| 47 |
} |
| 48 |
|
| 49 |
// IsEmpty will return true if no tickets are being held at that instant. |
| 50 |
// It is safe to call concurrently with Acquire and Release, though do note |
| 51 |
// that the result may then be unpredictable. |
| 52 |
func (s *Semaphore) IsEmpty() bool { |
| 53 |
return len(s.sem) == 0 |
| 54 |
} |