-
Notifications
You must be signed in to change notification settings - Fork 4
/
errgroup.go
80 lines (65 loc) · 1.35 KB
/
errgroup.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
79
80
package waitgroup
import (
"context"
"sync"
)
// An ErrorGroup is a collection of goroutines working on subtasks that are part of
// the same overall task.
type ErrorGroup struct {
size int
pool chan byte
cancel func()
wg sync.WaitGroup
errOnce sync.Once
err error
}
// NewErrorGroup returns a new ErrorGroup instance
func NewErrorGroup(ctx context.Context, size int) (*ErrorGroup, context.Context) {
ctx, cancel := context.WithCancel(ctx)
wg := &ErrorGroup{
size: size,
cancel: cancel,
}
if size > 0 {
wg.pool = make(chan byte, size)
}
return wg, ctx
}
// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.
func (g *ErrorGroup) Wait() error {
g.wg.Wait()
if g.cancel != nil {
g.cancel()
}
return g.err
}
// Add calls the given function in a new goroutine.
//
// The first call to return a non-nil error cancels the group; its error will be
// returned by Wait.
func (g *ErrorGroup) Add(closures ...func() error) {
for _, c := range closures {
closure := c
if g.size > 0 {
g.pool <- 1
}
g.wg.Add(1)
go func() {
defer func() {
if g.size > 0 {
<-g.pool
}
g.wg.Done()
}()
if err := closure(); err != nil {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel()
}
})
}
}()
}
}