-
Notifications
You must be signed in to change notification settings - Fork 30
/
counter.go
55 lines (46 loc) · 874 Bytes
/
counter.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 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package ratelimit
import (
"github.com/TeaOSLab/EdgeNode/internal/zero"
"sync"
)
type Counter struct {
count int
sem chan zero.Zero
done chan zero.Zero
closeOnce sync.Once
}
func NewCounter(count int) *Counter {
return &Counter{
count: count,
sem: make(chan zero.Zero, count),
done: make(chan zero.Zero),
}
}
func (this *Counter) Count() int {
return this.count
}
// Len 已占用数量
func (this *Counter) Len() int {
return len(this.sem)
}
func (this *Counter) Ack() bool {
select {
case this.sem <- zero.New():
return true
case <-this.done:
return false
}
}
func (this *Counter) Release() {
select {
case <-this.sem:
default:
// 总是能Release成功
}
}
func (this *Counter) Close() {
this.closeOnce.Do(func() {
close(this.done)
})
}