-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
86 lines (64 loc) · 1.27 KB
/
main.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
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func generateData() <-chan int {
data := make(chan int)
go func(data chan int) {
for i := 0; i < 10; i++ {
data <- i
}
close(data)
}(data)
return data
}
func fanIn(sources ...<-chan int) <-chan int {
target := make(chan int)
go func() {
defer close(target)
wg := sync.WaitGroup{}
for _, source := range sources {
wg.Add(1)
go func(source <-chan int, target chan int) {
defer wg.Done()
for val := range source {
target <- val
}
}(source, target)
}
wg.Wait()
}()
return target
}
func fanOut(data <-chan int) <-chan int {
target := make(chan int)
go func(data <-chan int) {
defer close(target)
for val := range data {
target <- val
}
}(data)
return target
}
func main() {
data1 := generateData()
data2 := generateData()
target := fanIn(data1, data2)
target1 := fanOut(target)
target2 := fanOut(target)
go func() {
for d := range target1 {
fmt.Printf("target1: %d\n", d)
}
}()
go func() {
for d := range target2 {
fmt.Printf("target2: %d\n", d)
}
}()
time.Sleep(1 * time.Second) // Easily use time.Sleep to wait them finished instead of sync.WaitGroup
fmt.Printf("expected 1 goroutine, got goroutine: %d\n", runtime.NumGoroutine())
}