-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor.go
100 lines (87 loc) · 1.85 KB
/
processor.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package parwork
import (
"errors"
"fmt"
"runtime"
"sync"
)
// Processor handles the generation, distribution and reporting or work
type Processor struct {
workers int
queue int
generator WorkGenerator
reporter WorkCollector
}
// New returns a new work processor with default worker, queue length and reporter.
// Optional definitions are available through the processor options variadic arguments.
// In case of a
// Workers: Number of CPU
// Queue: Number of CPU * 100
// Reporter: output to stdout
func New(g WorkGenerator, options ...Option) (*Processor, error) {
if g == nil {
return nil, errors.New("generator is nil")
}
p := &Processor{
workers: runtime.NumCPU(),
queue: runtime.NumCPU() * 100,
generator: g,
reporter: func(w Work) {
fmt.Println(w)
},
}
for _, opt := range options {
err := opt(p)
if err != nil {
return nil, err
}
}
return p, nil
}
// Process begins the parallel processing of work
func (p Processor) Process() {
pending := make(chan Work, p.queue)
done := make(chan Work, p.queue)
workers := sync.WaitGroup{}
collector := sync.WaitGroup{}
p.bootstrapWorkers(&workers, pending, done)
p.bootstrapReporter(&collector, done)
p.generateWork(pending)
close(pending)
workers.Wait()
close(done)
collector.Wait()
}
func (p Processor) bootstrapWorkers(wg *sync.WaitGroup, pending <-chan Work, done chan<- Work) {
wCount := 0
for wCount < p.workers {
wg.Add(1)
go func() {
for work := range pending {
work.Do()
done <- work
}
wg.Done()
}()
wCount++
}
}
func (p Processor) bootstrapReporter(wg *sync.WaitGroup, done <-chan Work) {
wg.Add(1)
go func() {
for work := range done {
p.reporter(work)
}
wg.Done()
}()
}
func (p Processor) generateWork(pending chan<- Work) {
for {
work := p.generator()
if work == nil {
break
} else {
pending <- work
}
}
}