summaryrefslogtreecommitdiff
path: root/executor/executor.go
blob: 22c12350bb0aa70798eb76a3d55f2fe8b5a4ef01 (plain)
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
package executor

import (
	"sync"
)

type ExecutionMethod int

const (
	Parallel ExecutionMethod = iota
	Serial
)

type ExecutionUnit func()

func (ep ExecutionMethod) ToString() string {
	switch ep {
	case Parallel:
		return "Parallel"
	case Serial:
		return "Serial"
	}
	return "Unrecognized execution method"
}

func Execute(executionMethod ExecutionMethod, executionUnits []ExecutionUnit) *sync.WaitGroup {
	waiter := &sync.WaitGroup{}

	// Make sure that we Add to the wait group all the execution units
	// before starting to run any -- there is a potential race condition
	// otherwise.
	(*waiter).Add(len(executionUnits))

	for _, executionUnit := range executionUnits {
		// Stupid capture in Go! Argh.
		executionUnit := executionUnit

		invoker := func() {
			executionUnit()
			(*waiter).Done()
		}
		switch executionMethod {
		case Parallel:
			go invoker()
		case Serial:
			invoker()
		default:
			panic("Invalid execution method value given.")
		}
	}

	return waiter
}