1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-28 16:06:07 +03:00

Add semaphore pattern

This commit is contained in:
Tamer Tas 2015-12-23 15:45:48 +02:00
parent c58a206366
commit cfd83425b6

46
semaphore.go Normal file
View File

@ -0,0 +1,46 @@
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")
)
type Interface interface {
Acquire() error
Release() error
}
type semaphore struct {
sem chan struct{}
timeout time.Duration
}
func New(tickets int, timeout time.Duration) Semaphore {
return &semaphore{
sem: make(chan struct{}, tickets),
timeout: timeout,
}
}
func (s *semaphore) Acquire() error {
select {
case s.sem <- struct{}{}:
return nil
case <-time.After(s.timeout):
return ErrNoTickets
}
}
func (s *semaphore) Release() error {
_, ok := <-s.sem
if !ok {
return ErrIllegalRelease
}
return nil
}