/
semaphore.go
55 lines (46 loc) · 1.16 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Copyright 2015 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
*/
package lib
type Semaphore struct {
ch chan struct{}
}
func NewSemaphore(size uint) *Semaphore {
s := make(chan struct{}, size)
return &Semaphore{s}
}
// Acquire increments the semaphore, blocking if necessary.
func (s *Semaphore) Acquire() {
s.ch <- struct{}{}
}
// TryAcquire increments the semaphore without blocking.
// Returns false if the semaphore was not acquired.
func (s *Semaphore) TryAcquire() bool {
select {
case s.ch <- struct{}{}:
return true
default:
return false
}
}
// Release decrements the semaphore. If this operation causes
// the semaphore value to be negative, then panics.
func (s *Semaphore) Release() {
select {
case _ = <-s.ch:
return
default:
panic("Semaphore was released without being acquired")
}
}
// Count returns the current value of the semaphore.
func (s *Semaphore) Count() uint {
return uint(len(s.ch))
}
// Size returns the maximum semaphore value.
func (s *Semaphore) Size() uint {
return uint(cap(s.ch))
}