-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathracegroup.go
70 lines (62 loc) · 1.43 KB
/
racegroup.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
62
63
64
65
66
67
68
69
70
// Package racegroup provides synchronization, and Context cancelation for
// groups of goroutines working on subtasks of a common task.
package racegroup
import (
"context"
"sync"
"sync/atomic"
)
// A Group is a collection of goroutines working on subtasks.
type Group struct {
wg sync.WaitGroup
cancel func()
errHandler func(error)
semaphore chan struct{}
desired int64
completed int64
}
// WithContext returns a new Group and an associated Context derived from ctx.
func WithContext(ctx context.Context, opts ...Option) (*Group, context.Context, error) {
ctx, cancel := context.WithCancel(ctx)
g := &Group{cancel: cancel, desired: 1}
for _, opt := range opts {
if err := opt(g); err != nil {
return nil, nil, err
}
}
return g, ctx, nil
}
// Wait blocks until all function calls from the Go method have returned.
func (g *Group) Wait() {
g.wg.Wait()
if g.cancel != nil {
g.cancel()
}
}
// Go calls the given function in a new goroutine.
//
// If more than or equal to desired count subtasks are completed,
// cancels the group.
func (g *Group) Go(f func() error) {
g.wg.Add(1)
if g.semaphore != nil {
g.semaphore <- struct{}{}
}
go func() {
defer g.wg.Done()
defer func() {
if g.semaphore != nil {
<-g.semaphore
}
}()
if err := f(); err != nil {
if g.errHandler != nil {
g.errHandler(err)
}
} else {
if atomic.AddInt64(&g.completed, 1) >= g.desired {
g.cancel()
}
}
}()
}