mirror of
https://github.com/tmrts/go-patterns.git
synced 2024-11-24 22:16:12 +03:00
Add semaphore pattern
This commit is contained in:
parent
c58a206366
commit
cfd83425b6
46
semaphore.go
Normal file
46
semaphore.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user