/
pool.go
59 lines (45 loc) · 1.06 KB
/
pool.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
package work
import (
"sync"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type Pool struct {
Count int
}
// ParallelDo Runs the given set of tasks in parallel using the configured number of worker go routines
// Will stop adding new tasks if a task throws an error, but will wait for in-flight tasks to finish
func (p Pool) ParallelDo(tasks ...func() error) error {
jobs := make(chan func() error, len(tasks))
errs := make(chan error, len(tasks))
wg := &sync.WaitGroup{}
wg.Add(p.Count)
for i := 0; i < p.Count; i++ {
p.spawnWorker(jobs, errs, wg)
}
for _, task := range tasks {
jobs <- task
}
close(jobs)
wg.Wait()
close(errs)
var combinedErrors []error
for e := range errs {
combinedErrors = append(combinedErrors, e)
}
if len(combinedErrors) > 0 {
return bosherr.NewMultiError(combinedErrors...)
}
return nil
}
func (p Pool) spawnWorker(tasks <-chan func() error, errs chan<- error, wg *sync.WaitGroup) {
go func() {
for task := range tasks {
err := task()
if err != nil {
errs <- err
break
}
}
wg.Done()
}()
}