-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
70 lines (57 loc) · 1.73 KB
/
group.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
package group
import "context"
// Group collects actions (functions) and runs them concurrently. When one action
// (function) returns, all actions are interrupted.
// The zero value of a Group is useful.
type Group struct {
actions []action
}
// NewGroup creates a new group
func NewGroup() *Group {
return &Group{}
}
// Add an action (function) to the group. Each action must be pre-emptable by an
// interrupt function. That is, if interrupt is invoked, execute should return.
// Also is must be safe to call interrupt even after execute has returned.
//
// The first action (function) to return interrupts all running actions.
// The error is passed to the interrupt functions and is returned by Run.
func (g *Group) Add(execute func(context.Context) error, interrupt func(error)) {
g.actions = append(g.actions, action{execute, interrupt})
}
// Run all actions (functions) concurrently.
// When the first action returns, all others are interrupted.
// Run only returns when all actions have exited.
// Run returns the error returned by the first existing action.
func (g *Group) Run() error {
if len(g.actions) == 0 {
return nil
}
var cancel context.CancelFunc
ctx := context.TODO()
ctx, cancel = context.WithCancel(ctx)
// Run each action.
errors := make(chan error, len(g.actions))
for _, a := range g.actions {
go func(a action) {
errors <- a.execute(ctx)
}(a)
}
// Wait for the first action to stop.
err := <-errors
cancel()
// Signal all actions to stop.
for _, a := range g.actions {
a.interrupt(err)
}
// Wait for all actions to stop.
for i := 1; i < cap(errors); i++ {
<-errors
}
// Return the original error.
return err
}
type action struct {
execute func(context.Context) error
interrupt func(error)
}