mirror of
https://github.com/tmrts/go-patterns.git
synced 2026-11-11 23:07:51 +03:00
Update semaphore pattern
This commit is contained in:
1 parent
b1ddd2651b
commit
87db8356b3
2 files changed
+46
-12
No files matched your search
@@ -0,0 +1,50 @@
|
||||
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")
|
||||
)
|
||||
|
||||
// Interface, typically a type, that satisfies semaphore.Interface
|
||||
// can be acquired and released.
|
||||
type Interface interface {
|
||||
Acquire() error
|
||||
Release() error
|
||||
}
|
||||
|
||||
type implementation struct {
|
||||
sem chan struct{}
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (s *implementation) Acquire() error {
|
||||
select {
|
||||
case s.sem <- struct{}{}:
|
||||
return nil
|
||||
case <-time.After(s.timeout):
|
||||
return ErrNoTickets
|
||||
}
|
||||
}
|
||||
|
||||
func (s *implementation) Release() error {
|
||||
select {
|
||||
case _ = <-s.sem:
|
||||
return nil
|
||||
case <-time.After(s.timeout):
|
||||
return ErrIllegalRelease
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func New(tickets int, timeout time.Duration) Interface {
|
||||
return &implementation{
|
||||
sem: make(chan struct{}, tickets),
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user