-
Notifications
You must be signed in to change notification settings - Fork 0
/
errgroupsem.go
57 lines (46 loc) · 936 Bytes
/
errgroupsem.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
package errgroupsem
import (
"context"
"sync"
"golang.org/x/sync/semaphore"
)
type ErrGroupSem struct {
cancel func()
wg sync.WaitGroup
errOnce sync.Once
err error
sem *semaphore.Weighted
}
func WithContext(ctx context.Context, limit int) (*ErrGroupSem, context.Context) {
ctx, cancel := context.WithCancel(ctx)
return &ErrGroupSem{cancel: cancel, sem: semaphore.NewWeighted(int64(limit))}, ctx
}
func (g *ErrGroupSem) Wait() error {
g.wg.Wait()
if g.cancel != nil {
g.cancel()
}
return g.err
}
func (g *ErrGroupSem) markFailed(err error) {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel()
}
})
}
func (g *ErrGroupSem) Go(ctx context.Context, f func() error) {
if err := g.sem.Acquire(ctx, 1); err != nil {
g.markFailed(err)
return
}
g.wg.Add(1)
go func() {
defer g.wg.Done()
defer g.sem.Release(1)
if err := f(); err != nil {
g.markFailed(err)
}
}()
}