generated from lovelysunlight/go-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conc.go
61 lines (50 loc) · 901 Bytes
/
conc.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
package conc
import (
"context"
"errors"
"runtime"
"sync"
)
type WaitGroup struct {
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
errch chan error
errors []error
}
type Task func(context.Context) error
func (g *WaitGroup) Go(f Task) {
g.wg.Add(1)
defer g.wg.Done()
if err := f(g.ctx); err != nil {
g.errch <- err
}
}
func (g *WaitGroup) Wait() error {
g.wg.Wait()
return errors.Join(g.errors...)
}
func (g *WaitGroup) background() {
for {
select {
case err := <-g.errch:
g.errors = append(g.errors, err)
case <-g.ctx.Done():
return
}
}
}
func New(ctx context.Context) *WaitGroup {
ctx, cancel := context.WithCancel(ctx)
wg := &WaitGroup{
ctx: ctx,
cancel: cancel,
errch: make(chan error),
errors: make([]error, 0),
}
go wg.background()
runtime.SetFinalizer(wg, func(wg *WaitGroup) {
wg.cancel()
})
return wg
}