mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-24 20:56:03 +03:00
fix semaphore pattern
This commit is contained in:
parent
6ec8f1ebb5
commit
3877727a5c
@ -5,23 +5,24 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//error info
|
||||||
var (
|
var (
|
||||||
ErrNoTickets = errors.New("semaphore: could not aquire semaphore")
|
ErrNoTickets = errors.New("could not acquire semaphore")
|
||||||
ErrIllegalRelease = errors.New("semaphore: can't release the semaphore without acquiring it first")
|
ErrIllegalRelease = errors.New("can't release the semaphore without acquiring it first")
|
||||||
)
|
)
|
||||||
|
|
||||||
// Interface contains the behavior of a semaphore that can be acquired and/or released.
|
// ISemaphore contains the behavior of a semaphore that can be acquired and/or released.
|
||||||
type Interface interface {
|
type ISemaphore interface {
|
||||||
Acquire() error
|
Acquire() error
|
||||||
Release() error
|
Release() error
|
||||||
}
|
}
|
||||||
|
|
||||||
type implementation struct {
|
type semp struct {
|
||||||
sem chan struct{}
|
sem chan struct{}
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *implementation) Acquire() error {
|
func (s *semp) Acquire() error {
|
||||||
select {
|
select {
|
||||||
case s.sem <- struct{}{}:
|
case s.sem <- struct{}{}:
|
||||||
return nil
|
return nil
|
||||||
@ -30,19 +31,19 @@ func (s *implementation) Acquire() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *implementation) Release() error {
|
func (s *semp) Release() error {
|
||||||
select {
|
select {
|
||||||
case _ = <-s.sem:
|
case <-s.sem:
|
||||||
return nil
|
return nil
|
||||||
case <-time.After(s.timeout):
|
case <-time.After(s.timeout):
|
||||||
return ErrIllegalRelease
|
return ErrIllegalRelease
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(tickets int, timeout time.Duration) Interface {
|
//New return a new Semaphore
|
||||||
return &implementation{
|
func New(tickets int, timeout time.Duration) ISemaphore {
|
||||||
|
return &semp{
|
||||||
sem: make(chan struct{}, tickets),
|
sem: make(chan struct{}, tickets),
|
||||||
timeout: timeout,
|
timeout: timeout,
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user