-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
batch.go
67 lines (57 loc) · 1.46 KB
/
batch.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
package carapace
import "sync"
type (
batch []Action
invokedBatch []InvokedAction
)
// Batch creates a batch of Actions that can be invoked in parallel.
func Batch(actions ...Action) batch {
return batch(actions)
}
// Invoke invokes contained Actions of the batch using goroutines.
func (b batch) Invoke(c Context) invokedBatch {
invokedActions := make([]InvokedAction, len(b))
functions := make([]func(), len(b))
for index, action := range b {
localIndex := index
localAction := action
functions[index] = func() {
invokedActions[localIndex] = localAction.Invoke(c)
}
}
parallelize(functions...)
return invokedActions
}
// ToA converts the batch to an implicitly merged action which is a shortcut for:
//
// ActionCallback(func(c Context) Action {
// return batch.Invoke(c).Merge().ToA()
// })
func (b batch) ToA() Action {
return ActionCallback(func(c Context) Action {
return b.Invoke(c).Merge().ToA()
})
}
// Merge merges Actions of a batch.
func (b invokedBatch) Merge() InvokedAction {
switch len(b) {
case 0:
return ActionValues().Invoke(Context{})
case 1:
return b[0]
default:
return b[0].Merge(b[1:]...)
}
}
// Parallelize parallelizes the function calls (https://stackoverflow.com/a/44402936)
func parallelize(functions ...func()) {
var waitGroup sync.WaitGroup
waitGroup.Add(len(functions))
defer waitGroup.Wait()
for _, function := range functions {
go func(copy func()) {
defer waitGroup.Done()
copy()
}(function)
}
}