-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
61 lines (49 loc) · 984 Bytes
/
monitor.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
56
57
58
59
60
61
package monitor
import (
"context"
"golang.org/x/sync/semaphore"
)
type ProducerConsumer struct {
n int
count int
full *semaphore.Weighted
empty *semaphore.Weighted
buffers []int
ctx context.Context
}
func NewProducerConsumer(n int) *ProducerConsumer {
p := &ProducerConsumer{
n: n,
count: 0,
full: semaphore.NewWeighted(int64(1)),
empty: semaphore.NewWeighted(int64(1)),
buffers: make([]int, 0, n),
ctx: context.TODO(),
}
p.full.Acquire(p.ctx, 1)
p.empty.Acquire(p.ctx, 1)
return p
}
func (pc *ProducerConsumer) Insert(i int) {
if pc.count == pc.n {
pc.full.Acquire(pc.ctx, 1)
}
pc.count++
pc.buffers = append(pc.buffers, i)
if pc.count == 1 {
pc.empty.Release(1)
}
}
func (pc *ProducerConsumer) Remove() int {
var res int
if pc.count == 0 {
pc.empty.Acquire(pc.ctx, 1)
}
pc.count--
res = pc.buffers[0]
pc.buffers = pc.buffers[1:]
if pc.count == pc.n-1 {
pc.full.Release(1)
}
return res
}