forked from SumoLogic/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttled_exec.go
45 lines (40 loc) · 1.01 KB
/
throttled_exec.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
package vsphere
import (
"context"
"sync"
)
// ThrottledExecutor provides a simple mechanism for running jobs in separate
// goroutines while limit the number of concurrent jobs running at any given time.
type ThrottledExecutor struct {
limiter chan struct{}
wg sync.WaitGroup
}
// NewThrottledExecutor creates a new ThrottlesExecutor with a specified maximum
// number of concurrent jobs
func NewThrottledExecutor(limit int) *ThrottledExecutor {
if limit == 0 {
panic("Limit must be > 0")
}
return &ThrottledExecutor{limiter: make(chan struct{}, limit)}
}
// Run schedules a job for execution as soon as possible while respecting the
// maximum concurrency limit.
func (t *ThrottledExecutor) Run(ctx context.Context, job func()) {
t.wg.Add(1)
go func() {
defer t.wg.Done()
select {
case t.limiter <- struct{}{}:
defer func() {
<-t.limiter
}()
job()
case <-ctx.Done():
return
}
}()
}
// Wait blocks until all scheduled jobs have finished
func (t *ThrottledExecutor) Wait() {
t.wg.Wait()
}