-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfixedprocess.go
69 lines (54 loc) · 1.63 KB
/
fixedprocess.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
package parallel
import "sync"
// FixedProcess types execute a specified number of operations on a given
// number of goroutines.
type FixedProcess struct {
// The number of goroutines the process should use when divvying up
// operations.
numRoutines int
// The process' wait group to use when waiting for goroutines to finish their
// execution.
group sync.WaitGroup
// The number of iterations in the current execution that have begun.
iteration safeInt
// The total number of iterations specified by the last call to Execute.
iterations int
}
// MARK: Initializers
// NewFixedProcess creates and returns a new parallel process with the
// specified number of goroutines.
func NewFixedProcess(numRoutines int) *FixedProcess {
return &FixedProcess{
numRoutines: numRoutines,
}
}
// MARK: Public methods
// Execute executes the fixed process for the specified number of operations.
func (p *FixedProcess) Execute(iterations int, operation Operation) {
p.iterations = iterations
p.iteration.set(0)
p.group.Add(p.numRoutines)
for n := 0; n < p.numRoutines; n++ {
go p.runRoutine(operation)
}
p.group.Wait()
}
// Stop stops the fixed process after all of the current operations have
// finished executing.
func (p *FixedProcess) Stop() {
p.iteration.set(p.iterations)
}
// NumRoutines returns the number of routines that the synced processes was
// initialized with.
func (p *FixedProcess) NumRoutines() int {
return p.numRoutines
}
// MARK: Private methods
func (p *FixedProcess) runRoutine(operation Operation) {
defer p.group.Done()
i := p.iteration.get()
for i < p.iterations {
operation(i)
i = p.iteration.add(1)
}
}