-
Notifications
You must be signed in to change notification settings - Fork 18
/
parallel.go
78 lines (67 loc) · 1.22 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
73
74
75
76
77
78
package compiler
import (
"context"
"golang.org/x/sync/errgroup"
)
type Parallel struct {
compiler *Compiler
parallelism int
work chan Work
}
func NewParallel(parallelism int) *Parallel {
return &Parallel{
compiler: New(),
parallelism: parallelism,
work: make(chan Work, 100),
}
}
func (t *Parallel) Dir() string {
return t.compiler.Dir()
}
func (t *Parallel) Cleanup() {
defer t.compiler.Cleanup()
close(t.work)
}
type Work struct {
Result *string
Name string
Target string
Source string
}
func (t *Parallel) Add(work Work) {
if work.Result == nil {
panic("work.Result not set")
}
if work.Name == "" {
panic("work.Name not set")
}
if work.Target == "" {
panic("work.Target not set")
}
if work.Source == "" {
panic("work.Source not set")
}
if *work.Result == "" {
t.work <- work
}
}
func (t *Parallel) Run(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < t.parallelism; i++ {
g.Go(func() error {
for {
select {
case w := <-t.work:
res, err := t.compiler.Compile(ctx, w.Name, w.Target, w.Source)
if err != nil {
return err
}
*w.Result = res
default:
return nil
}
}
})
}
return g.Wait()
}