-
Notifications
You must be signed in to change notification settings - Fork 11
/
wait_any.go
67 lines (58 loc) · 1.82 KB
/
wait_any.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
package asynctask
import (
"context"
"fmt"
)
// WaitAnyOptions defines options for WaitAny function
type WaitAnyOptions struct {
// FailOnAnyError set to true will indicate WaitAny to return on first error it sees.
FailOnAnyError bool
}
// WaitAny block current thread til any of task finished.
// first error from any tasks passed in will be returned if FailOnAnyError is set.
// first task end without error will end wait and return nil
func WaitAny(ctx context.Context, options *WaitAnyOptions, tasks ...Waitable) error {
tasksCount := len(tasks)
if tasksCount == 0 {
return nil
}
if options == nil {
options = &WaitAnyOptions{}
}
// 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 FailOnAnyError is set.
if options.FailOnAnyError {
return err
}
errList = append(errList, err)
} else {
// return immediately after first task completed.
return nil
}
case <-ctx.Done():
return fmt.Errorf("WaitAny %w", ctx.Err())
}
// are we finished yet?
if runningTasks == 0 {
break
}
}
// when all tasks failed and FailOnAnyError is not set, return first one.
// caller can get error for individual task by using Wait(),
// it would return immediately after this WaitAny()
return errList[0]
}