awesome-patterns/semaphore/semaphore.go

51 lines
936 B
Go
Raw Normal View History

2015-12-23 16:45:48 +03:00
package semaphore
import (
"errors"
"time"
)
var (
ErrNoTickets = errors.New("semaphore: could not aquire semaphore")
ErrIllegalRelease = errors.New("semaphore: can't release the semaphore without acquiring it first")
)
2016-01-04 07:15:29 +03:00
// Interface, typically a type, that satisfies semaphore.Interface
// can be acquired and released.
2015-12-23 16:45:48 +03:00
type Interface interface {
Acquire() error
Release() error
}
2016-01-04 07:15:29 +03:00
type implementation struct {
2015-12-23 16:45:48 +03:00
sem chan struct{}
timeout time.Duration
}
2016-01-04 07:15:29 +03:00
func (s *implementation) Acquire() error {
2015-12-23 16:45:48 +03:00
select {
case s.sem <- struct{}{}:
return nil
case <-time.After(s.timeout):
return ErrNoTickets
}
}
2016-01-04 07:15:29 +03:00
func (s *implementation) Release() error {
select {
case _ = <-s.sem:
return nil
case <-time.After(s.timeout):
2015-12-23 16:45:48 +03:00
return ErrIllegalRelease
}
return nil
}
2016-01-04 07:15:29 +03:00
func New(tickets int, timeout time.Duration) Interface {
return &implementation{
sem: make(chan struct{}, tickets),
timeout: timeout,
}
}