-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparallel.go
59 lines (43 loc) · 972 Bytes
/
parallel.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 bigopool
import (
"context"
"sync"
)
// Parallel runs multiple functions in parallel and collects the errors safely.
func Parallel(ff ...func() error) Errors {
var wg sync.WaitGroup
var ee errs
wg.Add(len(ff))
for i := range ff {
f := ff[i]
go func() {
defer wg.Done()
if err := f(); err != nil {
ee.append(err)
}
}()
}
wg.Wait()
return &ee
}
// CancelableParallel runs multiple functions in parallel and collects the errors safely, while canceling the context
// passed to the remaining functions as soon as a function returns an error.
func CancelableParallel(ctx context.Context, ff ...func(context.Context) error) Errors {
var wg sync.WaitGroup
var ee errs
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
wg.Add(len(ff))
for i := range ff {
f := ff[i]
go func() {
defer wg.Done()
if err := f(cancelCtx); err != nil {
cancel()
ee.append(err)
}
}()
}
wg.Wait()
return &ee
}