Skip to content

Commit 976cdc7

Browse files
committed
add util/errgroup.go to collect all errors
1 parent 99c1d6a commit 976cdc7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

pbm/util/errgroup.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package util
2+
3+
import (
4+
"runtime"
5+
"sync"
6+
)
7+
8+
type errorGroup struct {
9+
errs []error
10+
mu sync.Mutex
11+
12+
wg sync.WaitGroup
13+
sem chan struct{}
14+
}
15+
16+
func NewErrorGroup(limit int) *errorGroup {
17+
if limit <= 0 {
18+
limit = runtime.NumCPU()
19+
}
20+
return &errorGroup{sem: make(chan struct{}, limit)}
21+
}
22+
23+
func (g *errorGroup) Wait() []error {
24+
g.wg.Wait()
25+
return g.errs
26+
}
27+
28+
func (g *errorGroup) Go(f func() error) {
29+
g.wg.Add(1)
30+
go func() {
31+
g.sem <- struct{}{}
32+
33+
defer func() {
34+
<-g.sem
35+
g.wg.Done()
36+
}()
37+
38+
if err := f(); err != nil {
39+
g.mu.Lock()
40+
g.errs = append(g.errs, err)
41+
g.mu.Unlock()
42+
}
43+
}()
44+
}

0 commit comments

Comments
 (0)