File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ package errgroup
2+
3+ import (
4+ "sync"
5+
6+ "golang.org/x/net/context"
7+ )
8+
9+ // A Group is a collection of goroutines working on subtasks that are part of
10+ // the same overall task.
11+ //
12+ // A zero Group is valid and does not cancel on error.
13+ type Group struct {
14+ cancel func ()
15+
16+ wg sync.WaitGroup
17+
18+ errOnce sync.Once
19+ err error
20+ }
21+
22+ // WithContext returns a new Group and an associated Context derived from ctx.
23+ //
24+ // The derived Context is canceled the first time a function passed to Go
25+ // returns a non-nil error or the first time Wait returns, whichever occurs
26+ // first.
27+ func WithContext (ctx context.Context ) (* Group , context.Context ) {
28+ ctx , cancel := context .WithCancel (ctx )
29+ return & Group {cancel : cancel }, ctx
30+ }
31+
32+ // Wait blocks until all function calls from the Go method have returned, then
33+ // returns the first non-nil error (if any) from them.
34+ func (g * Group ) Wait () error {
35+ g .wg .Wait ()
36+ if g .cancel != nil {
37+ g .cancel ()
38+ }
39+ return g .err
40+ }
41+
42+ // Stop cancels all goroutines
43+ func (g * Group ) Stop () error {
44+ if g .cancel != nil {
45+ g .cancel ()
46+ }
47+ return g .err
48+ }
49+
50+ // Go calls the given function in a new goroutine.
51+ //
52+ // The first call to return a non-nil error cancels the group; its error will be
53+ // returned by Wait.
54+ func (g * Group ) Go (f func () error ) {
55+ g .wg .Add (1 )
56+
57+ go func () {
58+ defer g .wg .Done ()
59+
60+ if err := f (); err != nil {
61+ g .errOnce .Do (func () {
62+ g .err = err
63+ if g .cancel != nil {
64+ g .cancel ()
65+ }
66+ })
67+ }
68+ }()
69+ }
You can’t perform that action at this time.
0 commit comments