-
Notifications
You must be signed in to change notification settings - Fork 6
/
group.go
81 lines (68 loc) · 1.51 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
70
71
72
73
74
75
76
77
78
79
80
81
package parallelizer
import (
"errors"
"sync"
)
const (
nilFunctionError = "nil function"
)
// NewGroup create a new group of workers
func NewGroup(options ...GroupOption) *Group {
groupOptions := newGroupOptions(options...)
group := &Group{
jobsChannel: make(chan func() error, groupOptions.JobQueueSize),
errorChannel: make(chan error),
waitGroup: &sync.WaitGroup{},
}
for i := 1; i <= groupOptions.PoolSize; i++ {
go group.worker()
}
return group
}
// Group a group of workers executing functions concurrently
type Group struct {
jobsChannel chan func() error
errorChannel chan error
waitGroup *sync.WaitGroup
}
// Add adds function to queue of jobs to execute
func (g *Group) Add(function func() error) error {
if function == nil {
return errors.New(nilFunctionError)
}
g.waitGroup.Add(1)
g.jobsChannel <- function
return nil
}
// Wait waits until workers finished the jobs in the queue
func (g *Group) Wait(options ...WaitOption) error {
waitOptions := newWaitOptions(options...)
waitChannel := make(chan bool)
go func() {
g.waitGroup.Wait()
close(waitChannel)
}()
select {
case <-waitOptions.Context.Done():
return waitOptions.Context.Err()
case err := <-g.errorChannel:
return err
case <-waitChannel:
return nil
}
}
// Close closes resources
func (g *Group) Close() {
close(g.jobsChannel)
close(g.errorChannel)
}
func (g *Group) worker() {
for job := range g.jobsChannel {
err := job()
if err != nil {
g.errorChannel <- err
return
}
g.waitGroup.Done()
}
}