Skip to content

Commit abcdf32

Browse files
committed
Rewrite semaphore pattern
1 parent 51e0aeb commit abcdf32

File tree

3 files changed

+42
-38
lines changed

3 files changed

+42
-38
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ __Synchronization Patterns__:
5757
| [Lock/Mutex](mutex/mutex.go) | Enforces mutual exclusion limit on a resource to gain exclusive access |
5858
| [Monitor](monitor.go) | Combination of mutex and condition variable patterns |
5959
| [Read-Write Lock](read_write_lock.go) | Allows parallel read access, but only exclusive access on write operations to a resource |
60-
| [Semaphore](semaphore/semaphore.go) | Allows controlling access to a common resource |
60+
| [Semaphore](synchronization/semaphore.md) | Allows controlling access to a common resource |
6161

6262
__Concurrency Patterns__:
6363

semaphore/semaphore_test.go

-30
This file was deleted.

semaphore/semaphore.go renamed to synchronization/semaphore.md

+41-7
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
package semaphore
1+
# Semaphore Pattern
2+
A semaphore is a synchronization pattern/primitive that imposes mutual exclusion on a limited number of resources.
23

3-
import (
4-
"errors"
5-
"time"
6-
)
4+
## Implementation
5+
6+
```go
7+
package semaphore
78

89
var (
910
ErrNoTickets = errors.New("semaphore: could not aquire semaphore")
1011
ErrIllegalRelease = errors.New("semaphore: can't release the semaphore without acquiring it first")
1112
)
1213

13-
// Interface, typically a type, that satisfies semaphore.Interface
14-
// can be acquired and released.
14+
// Interface contains the behavior of a semaphore that can be acquired and/or released.
1515
type Interface interface {
1616
Acquire() error
1717
Release() error
@@ -48,3 +48,37 @@ func New(tickets int, timeout time.Duration) Interface {
4848
timeout: timeout,
4949
}
5050
}
51+
```
52+
53+
## Usage
54+
### Semaphore with Timeouts
55+
56+
```go
57+
tickets, timeout := 1, 3*time.Second
58+
s := semaphore.New(tickets, timeout)
59+
60+
if err := s.Acquire(); err != nil {
61+
panic(err)
62+
}
63+
64+
// Do important work
65+
66+
if err := s.Release(); err != nil {
67+
panic(err)
68+
}
69+
```
70+
### Semaphore without Timeouts (Non-Blocking)
71+
72+
```go
73+
tickets, timeout := 0, 0
74+
s := semaphore.New(tickets, timeout)
75+
76+
if err := s.Acquire(); err != nil {
77+
if err != semaphore.ErrNoTickets {
78+
panic(err)
79+
}
80+
81+
// No tickets left, can't work :(
82+
os.Exit(1)
83+
}
84+
```

0 commit comments

Comments
 (0)