-
Notifications
You must be signed in to change notification settings - Fork 6
/
numGoRoutinesThrottler.go
46 lines (36 loc) · 1.12 KB
/
numGoRoutinesThrottler.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
package throttler
import (
"sync/atomic"
"github.com/ElrondNetwork/elrond-go-core/core"
)
// NumGoRoutinesThrottler can limit the number of go routines launched
type NumGoRoutinesThrottler struct {
max int32
counter int32
}
// NewNumGoRoutinesThrottler creates a new num go routine throttler instance
func NewNumGoRoutinesThrottler(max int32) (*NumGoRoutinesThrottler, error) {
if max <= 0 {
return nil, core.ErrNotPositiveValue
}
return &NumGoRoutinesThrottler{
max: max,
}, nil
}
// CanProcess returns true if current counter is less than max
func (ngrt *NumGoRoutinesThrottler) CanProcess() bool {
valCounter := atomic.LoadInt32(&ngrt.counter)
return valCounter < ngrt.max
}
// StartProcessing will increment current counter
func (ngrt *NumGoRoutinesThrottler) StartProcessing() {
atomic.AddInt32(&ngrt.counter, 1)
}
// EndProcessing will decrement current counter
func (ngrt *NumGoRoutinesThrottler) EndProcessing() {
atomic.AddInt32(&ngrt.counter, -1)
}
// IsInterfaceNil returns true if there is no value under the interface
func (ngrt *NumGoRoutinesThrottler) IsInterfaceNil() bool {
return ngrt == nil
}