-
Notifications
You must be signed in to change notification settings - Fork 3
/
group.go
69 lines (59 loc) · 1.41 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package wait
import (
"context"
"sync"
"time"
)
// Group is wrapper over sync.WaitGroup
type Group struct {
wg sync.WaitGroup
}
// Add function calling argument function in a separate goroutine with sync.WaitGroup control
func (g *Group) Add(f func()) {
g.wg.Add(1)
go func() {
defer g.wg.Done()
f()
}()
}
// AddWithContext function calling argument function with context
// in a separate goroutine with sync.WaitGroup control
func (g *Group) AddWithContext(ctx context.Context, f func(context.Context)) {
g.wg.Add(1)
go func() {
defer g.wg.Done()
f(ctx)
}()
}
// AddMany running call group.Add count times
func (g *Group) AddMany(count int, f func()) {
for i := 0; i < count; i++ {
g.Add(f)
}
}
// AddManyWithContext running call group.AddWithContext count times
func (g *Group) AddManyWithContext(ctx context.Context, count int, f func(context.Context)) {
for i := 0; i < count; i++ {
g.AddWithContext(ctx, f)
}
}
// Wait blocks until all added functions will be completed
func (g *Group) Wait() {
g.wg.Wait()
}
// WaitTimeout waits works group and return error by timeout if some goroutine dont finished
func (g *Group) WaitTimeout(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
done := make(chan struct{})
go func() {
g.wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
return nil
}
}