-
Notifications
You must be signed in to change notification settings - Fork 2
/
parallel.go
72 lines (55 loc) · 1.33 KB
/
parallel.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
package parallel
import (
"sync"
)
// Func is the function to run concurrently.
type Func func() error
// Run calls the passed functions in a goroutine, returns a chan of errors.
func Run(functions ...Func) chan error {
total := len(functions)
errs := make(chan error, total)
var wg sync.WaitGroup
wg.Add(total)
go func(errs chan error) {
wg.Wait()
close(errs)
}(errs)
for _, fn := range functions {
go func(fn Func, errs chan error) {
defer wg.Done()
errs <- fn()
}(fn, errs)
}
return errs
}
// RunLimit calls the passed functions in a goroutine, limiting the number of goroutines running at the same time,
// returns a chan of errors.
func RunLimit(concurrency int, functions ...Func) chan error {
total := len(functions)
if concurrency <= 0 {
concurrency = 1
}
if concurrency > total {
concurrency = total
}
var wg sync.WaitGroup
wg.Add(total)
errs := make(chan error, total)
go func(errs chan error) {
wg.Wait()
close(errs)
}(errs)
sem := make(chan struct{}, concurrency)
defer func(sem chan<- struct{}) { close(sem) }(sem)
for _, fn := range functions {
go func(fn Func, sem <-chan struct{}, errs chan error) {
defer wg.Done()
defer func(sem <-chan struct{}) { <-sem }(sem)
errs <- fn()
}(fn, sem, errs)
}
for i := 0; i < cap(sem); i++ {
sem <- struct{}{}
}
return errs
}