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

Update semaphore pattern

This commit is contained in:
Tamer Tas 2016-01-04 06:15:29 +02:00
parent b1ddd2651b
commit 87db8356b3
2 changed files with 46 additions and 12 deletions

View File

@ -10,24 +10,19 @@ var (
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 semaphore struct {
type implementation 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 {
func (s *implementation) Acquire() error {
select {
case s.sem <- struct{}{}:
return nil
@ -36,11 +31,20 @@ func (s *semaphore) Acquire() error {
}
}
func (s *semaphore) Release() error {
_, ok := <-s.sem
if !ok {
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,
}
}

View File

@ -0,0 +1,30 @@
package semaphore_test
import (
"testing"
"time"
"github.com/tmrts/go-patterns/semaphore"
)
func TestCreatesSemaphore(t *testing.T) {
tickets, timeout := 1, 3*time.Second
s := semaphore.New(tickets, timeout)
if err := s.Acquire(); err != nil {
t.Errorf("semaphore.Acquire() got errors %s", err)
}
if err := s.Release(); err != nil {
t.Errorf("semaphore.Release() got errors %s", err)
}
}
func TestCreatesNonBlockingSemaphore(t *testing.T) {
tickets, timeout := 0, 0
s := semaphore.New(tickets, timeout)
if err := s.Acquire(); err != semaphore.ErrIllegalRelease {
t.Errorf("non-blocking semaphore.Acquire() expected error %s got %s", semaphore.ErrIllegalRelease, err)
}
}