-
Notifications
You must be signed in to change notification settings - Fork 20
/
pipeline-split.go
74 lines (59 loc) · 1.06 KB
/
pipeline-split.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
package main
import (
"context"
"log"
"sync"
)
func main() {
generator := func(n int) <-chan interface{} {
stream := make(chan interface{})
go func() {
defer close(stream)
for i := 0; i < n; i++ {
stream <- i
}
}()
return stream
}
split := func(ctx context.Context, in <-chan interface{}) (<-chan interface{}, <-chan interface{}) {
out1 := make(chan interface{})
out2 := make(chan interface{})
go func() {
defer close(out1)
defer close(out2)
for i := range in {
select {
case out1 <- i:
case <-ctx.Done():
return
}
select {
case out2 <- i:
case <-ctx.Done():
return
}
}
}()
return out1, out2
}
var wg sync.WaitGroup
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
wg.Add(2)
o1, o2 := split(ctx, generator(10))
go func() {
defer wg.Done()
for o := range o1 {
log.Println("split 1:", o)
}
}()
go func() {
defer wg.Done()
for o := range o2 {
log.Println("split 2:", o)
}
}()
wg.Wait()
log.Println("terminating program")
}