forked from Velocidex/velociraptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrency.go
50 lines (41 loc) · 1.16 KB
/
concurrency.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
package utils
import (
"context"
"time"
errors "github.com/go-errors/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
concurrencyControl = promauto.NewGauge(prometheus.GaugeOpts{
Name: "client_comms_concurrency",
Help: "The total number of currently executing client receive operations",
})
)
type Concurrency struct {
concurrency chan bool
timeout time.Duration
}
func (self *Concurrency) StartConcurrencyControl(ctx context.Context) (func(), error) {
// Wait here until we have enough room in the concurrency
// channel.
select {
case self.concurrency <- true:
concurrencyControl.Inc()
return self.EndConcurrencyControl, nil
case <-ctx.Done():
return nil, errors.New("Concurrency: Timed out due to cancellation")
case <-time.After(self.timeout):
return nil, errors.New("Timed out in concurrency control")
}
}
func (self *Concurrency) EndConcurrencyControl() {
<-self.concurrency
concurrencyControl.Dec()
}
func NewConcurrencyControl(size int, timeout time.Duration) *Concurrency {
return &Concurrency{
timeout: timeout,
concurrency: make(chan bool, size),
}
}