-
Notifications
You must be signed in to change notification settings - Fork 17
/
parallel.go
79 lines (67 loc) · 1.27 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
79
/*
Package compiler aids with compiling your Go binaries efficiently and in a consistent way.
*/
package compiler
import (
"context"
"golang.org/x/sync/errgroup"
)
type Config struct {
BaseDir string
LDFlags string
Parallelism int
}
type Parallel struct {
compiler *compiler
parallelism int
work chan Work
}
func New(cfg Config) *Parallel {
if cfg.Parallelism <= 0 {
cfg.Parallelism = 2
}
return &Parallel{
compiler: newCompiler(cfg.BaseDir, cfg.LDFlags),
parallelism: cfg.Parallelism,
work: make(chan Work, 100),
}
}
func (t *Parallel) Dir() string {
return t.compiler.Dir()
}
func (t *Parallel) Cleanup() {
close(t.work)
}
func (t *Parallel) Add(work Work) {
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 == nil || *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:
_, err := t.compiler.Compile(ctx, w)
if err != nil {
return err
}
default:
return nil
}
}
})
}
return g.Wait()
}