-
Notifications
You must be signed in to change notification settings - Fork 0
/
fan_out_fan_in.go
93 lines (81 loc) · 1.74 KB
/
fan_out_fan_in.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
package pipelines
import "context"
type WorkerFunc[Arg, Res any] func(ctx context.Context, in Arg) Res
func FanOut[In, Out any](ctx context.Context, inStream <-chan In, maxProcs int, workerFunc WorkerFunc[In, Out]) <-chan (<-chan Out) {
chanStream := make(chan (<-chan Out))
if inStream == nil {
close(chanStream)
panic("FanOut: inStream arg has nil value")
}
if workerFunc == nil {
close(chanStream)
panic("FanOut: workerFunc arg has nil value")
}
go func() {
defer close(chanStream)
for i := 0; i < maxProcs; i++ {
select {
case <-ctx.Done():
return
case chanStream <- WorkerThread(ctx, inStream, workerFunc):
}
}
}()
return chanStream
}
func WorkerThread[In, Out any](ctx context.Context, inStream <-chan In, workerFunc WorkerFunc[In, Out]) <-chan Out {
resStream := make(chan Out)
if inStream == nil {
close(resStream)
panic("WorkerThread: provided stream has nil value")
}
go func() {
defer close(resStream)
for {
select {
case <-ctx.Done():
return
case item, ok := <-inStream:
if !ok {
return
}
select {
case resStream <- workerFunc(ctx, item):
case <-ctx.Done():
return
}
}
}
}()
return resStream
}
func FanIn[T any](ctx context.Context, chanStream <-chan (<-chan T)) chan T {
outStream := make(chan T)
if chanStream == nil {
close(outStream)
panic("FanIn: chanStream has nil value")
}
go func() {
defer close(outStream)
for {
var possStream <-chan T
select {
case chn, ok := <-chanStream:
if !ok {
return
}
possStream = chn
case <-ctx.Done():
return
}
for t := range OrDone(ctx, possStream) {
select {
case outStream <- t:
case <-ctx.Done():
return
}
}
}
}()
return outStream
}