-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bcast.go
98 lines (86 loc) · 1.95 KB
/
bcast.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
package pipeline
import (
"context"
"sync"
"github.com/caffix/queue"
)
type broadcast struct {
id string
fifos []Stage
inChs []chan Data
}
// Broadcast returns a Stage that passes a copy of each incoming data
// to all specified tasks and emits their outputs to the next stage.
func Broadcast(id string, tasks ...Task) Stage {
if len(tasks) == 0 {
return nil
}
fifos := make([]Stage, len(tasks))
for i, t := range tasks {
fifos[i] = FIFO("", t)
}
return &broadcast{
id: id,
fifos: fifos,
inChs: make([]chan Data, len(fifos)),
}
}
// ID implements Stage.
func (b *broadcast) ID() string {
return b.id
}
// Run implements Stage.
func (b *broadcast) Run(ctx context.Context, sp StageParams) {
var wg sync.WaitGroup
// Start each FIFO in a goroutine. Each FIFO gets its own dedicated
// input channel and the shared output channel passed to Run.
for i := 0; i < len(b.fifos); i++ {
wg.Add(1)
b.inChs[i] = make(chan Data)
go func(idx int) {
b.fifos[idx].Run(ctx, ¶ms{
stage: sp.Position(),
inCh: b.inChs[idx],
outCh: sp.Output(),
dataQueue: queue.NewQueue(),
errQueue: sp.Error(),
registry: sp.Registry(),
})
wg.Done()
}(i)
}
for {
// Read incoming data and pass them to each FIFO
if !processStageData(ctx, sp, b.executeTask) {
break
}
}
// Close input channels and wait for FIFOs to exit
for _, ch := range b.inChs {
close(ch)
}
wg.Wait()
}
func (b *broadcast) executeTask(ctx context.Context, data Data, sp StageParams) (Data, error) {
select {
case <-ctx.Done():
return nil, nil
default:
}
for i := len(b.fifos) - 1; i >= 0; i-- {
fifoData := data
// As each FIFO might modify the data, to
// avoid data races we need to make a copy
// of the data for all FIFOs except the first.
if i != 0 {
fifoData = data.Clone()
}
select {
case <-ctx.Done():
return nil, nil
case b.inChs[i] <- fifoData:
// data sent to i_th FIFO
}
}
return data, nil
}