-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
semaphore.go
42 lines (35 loc) · 902 Bytes
/
semaphore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package syncs
import "sync"
// Locker is a superset of sync.Locker interface with TryLock method.
type Locker interface {
sync.Locker
TryLock() bool
}
// Semaphore implementation, counted lock only. Implements Locker interface, thread safe.
type semaphore struct {
ch chan struct{}
}
// NewSemaphore makes Semaphore with given capacity
func NewSemaphore(capacity int) Locker {
if capacity <= 0 {
capacity = 1
}
return &semaphore{ch: make(chan struct{}, capacity)}
}
// Lock acquires semaphore, can block if out of capacity.
func (s *semaphore) Lock() {
s.ch <- struct{}{}
}
// Unlock releases semaphore, can block if nothing acquired before.
func (s *semaphore) Unlock() {
<-s.ch
}
// TryLock acquires semaphore if possible, returns true if acquired, false otherwise.
func (s *semaphore) TryLock() bool {
select {
case s.ch <- struct{}{}:
return true
default:
return false
}
}