-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecute.go
56 lines (45 loc) · 950 Bytes
/
execute.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
package parallel
import (
"sync"
)
// Execute executes multiple callback functions `cbs` in parallel.
func Execute(cbs ...func() error) []error {
var errs []error
wg := sync.WaitGroup{}
for i := range cbs {
wg.Add(1)
go func(idx int) {
defer func() {
wg.Done()
}()
if err := cbs[idx](); err != nil {
errs = append(errs, err)
}
}(i)
}
wg.Wait()
return errs
}
// ExecuteOpts executes slice of callback functions `cbs` with custom options.
func ExecuteOpts(cbs []func() error, opts ...ExecuteOption) []error {
var errs []error
ops := parseExecuteOptions(opts)
wg := sync.WaitGroup{}
// init goroutines limiter
limiter := NewConcurrencyLimiter(ops.concurrency)
for i := range cbs {
limiter.Acquire()
wg.Add(1)
go func(idx int) {
defer func() {
limiter.Release()
wg.Done()
}()
if err := cbs[idx](); err != nil {
errs = append(errs, err)
}
}(i)
}
wg.Wait()
return errs
}