-
Notifications
You must be signed in to change notification settings - Fork 1
/
ctxgroup.go
54 lines (45 loc) · 1016 Bytes
/
ctxgroup.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
package synx
import (
"context"
"sync"
)
// ContextGroup is simple wrapper around sync.WaitGroup.
type ContextGroup struct {
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
errOnce sync.Once
err error
}
// NewContextGroup returns new ContextGroup.
func NewContextGroup(parent context.Context) *ContextGroup {
ctx, cancel := context.WithCancel(parent)
return &ContextGroup{
ctx: ctx,
cancel: cancel,
}
}
// Go calls the given function in a new goroutine.
func (cg *ContextGroup) Go(f func(context.Context) error) {
cg.wg.Add(1)
go func() {
defer cg.wg.Done()
if err := f(cg.ctx); err != nil {
cg.errOnce.Do(func() {
cg.err = err
cg.cancel()
})
}
}()
}
// Cancel cancels all goroutines in the group.
func (cg *ContextGroup) Cancel() {
cg.cancel()
}
// WaitErr blocks until all function calls have returned.
// Returns the first non-nil error (if any).
func (cg *ContextGroup) WaitErr() error {
cg.wg.Wait()
cg.cancel()
return cg.err
}