forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup.go
46 lines (38 loc) · 915 Bytes
/
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
package syncs
import (
"context"
"golang.org/x/sync/errgroup"
)
// ErrGroup is a collection of goroutines working on subtasks that
// are part of the same overall task.
//
// Refers:
//
// https://github.com/neilotoole/errgroup
// https://github.com/fatih/semgroup
type ErrGroup struct {
*errgroup.Group
}
// NewCtxErrGroup instance
func NewCtxErrGroup(ctx context.Context, limit ...int) (*ErrGroup, context.Context) {
egg, ctx1 := errgroup.WithContext(ctx)
if len(limit) > 0 && limit[0] > 0 {
egg.SetLimit(limit[0])
}
eg := &ErrGroup{Group: egg}
return eg, ctx1
}
// NewErrGroup instance
func NewErrGroup(limit ...int) *ErrGroup {
eg := &ErrGroup{Group: new(errgroup.Group)}
if len(limit) > 0 && limit[0] > 0 {
eg.SetLimit(limit[0])
}
return eg
}
// Add one or more handler at once
func (g *ErrGroup) Add(handlers ...func() error) {
for _, handler := range handlers {
g.Go(handler)
}
}