-
Notifications
You must be signed in to change notification settings - Fork 11
/
wait_all.go
78 lines (65 loc) · 1.81 KB
/
wait_all.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package asynctask
import (
"context"
"fmt"
)
type Waitable interface {
Wait(context.Context) error
}
// WaitAllOptions defines options for WaitAll function
type WaitAllOptions struct {
// FailFast set to true will indicate WaitAll to return on first error it sees.
FailFast bool
}
// WaitAll block current thread til all task finished.
// first error from any tasks passed in will be returned.
func WaitAll(ctx context.Context, options *WaitAllOptions, tasks ...Waitable) error {
tasksCount := len(tasks)
if tasksCount == 0 {
return nil
}
if options == nil {
options = &WaitAllOptions{}
}
// tried to close channel before exit this func,
// but it's complicated with routines, and we don't want to delay the return.
// per https://stackoverflow.com/questions/8593645/is-it-ok-to-leave-a-channel-open, its ok to leave channel open, eventually it will be garbage collected.
// this assumes the tasks eventually finish, otherwise we will have a routine leak.
errorCh := make(chan error, tasksCount)
for _, tsk := range tasks {
go waitOne(ctx, tsk, errorCh)
}
runningTasks := tasksCount
var errList []error
for {
select {
case err := <-errorCh:
runningTasks--
if err != nil {
// return immediately after receive first error.
if options.FailFast {
return err
}
errList = append(errList, err)
}
case <-ctx.Done():
return fmt.Errorf("WaitAll %w", ctx.Err())
}
// are we finished yet?
if runningTasks == 0 {
break
}
}
// we have at least 1 error, return first one.
// caller can get error for individual task by using Wait(),
// it would return immediately after this WaitAll()
if len(errList) > 0 {
return errList[0]
}
// no error at all.
return nil
}
func waitOne(ctx context.Context, tsk Waitable, errorCh chan<- error) {
err := tsk.Wait(ctx)
errorCh <- err
}