-
Notifications
You must be signed in to change notification settings - Fork 38
/
tasks.go
60 lines (45 loc) · 983 Bytes
/
tasks.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
package utils
import "sync"
type Task func() error
type Tasks []Task
type Errors []error
func RunParallelTasks(tasks Tasks, parallel bool) (errors Errors) {
if !parallel {
for _, task := range tasks {
if error := task(); error != nil {
errors = append(errors, error)
return
}
}
return
}
waitGroup := sync.WaitGroup{}
waitGroup.Add(len(tasks))
errorChannel := make(chan error, 1)
finishedChannel := make(chan bool, 1)
// Schedule tasks to be executed
for _, task := range tasks {
go func(_task Task) {
if error := _task(); error != nil {
errorChannel <- error
}
waitGroup.Done()
}(task)
}
// Wait for all tasks to be done and send notification
go func() {
waitGroup.Wait()
close(finishedChannel)
}()
done := false
// Collect errors and wait for all tasks to be done
for !done {
select {
case <-finishedChannel:
done = true
case error := <-errorChannel:
errors = append(errors, error)
}
}
return
}