-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_limiter.go
59 lines (52 loc) · 1.16 KB
/
concurrent_limiter.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
package common
// ConcurrentLimiter can limit the concurrent of centain code block
type ConcurrentLimiter struct {
Enabled bool
sem chan bool
}
// NewConcurrentLimiter creates a new limiter
func NewConcurrentLimiter(maxConcurrent int) *ConcurrentLimiter {
sem := make(chan bool, maxConcurrent)
if maxConcurrent <= 0 {
return &ConcurrentLimiter{
false, sem,
}
}
return &ConcurrentLimiter{
true, sem,
}
}
// Begin call this function before the actuall logic
func (p *ConcurrentLimiter) Begin() bool {
if p.Enabled {
select {
case p.sem <- true:
return true
default:
return false
}
}
return true
}
// End release a concurrent lock
func (p *ConcurrentLimiter) End() bool {
if p.Enabled {
<-p.sem
}
return true
}
// GetCurrentSize returns how many go routines is current running
func (p *ConcurrentLimiter) GetCurrentSize() int {
return len(p.sem)
}
// GetMaxCocurrent gets the capacity of the limiter
func (p *ConcurrentLimiter) GetMaxCocurrent() int {
return cap(p.sem)
}
// IsFull returns if cocurrentcy limit is reached
func (p *ConcurrentLimiter) IsFull() bool {
if !p.Enabled {
return false
}
return len(p.sem) >= cap(p.sem)
}