-
Notifications
You must be signed in to change notification settings - Fork 86
/
hi_fan.go
76 lines (62 loc) · 1 KB
/
hi_fan.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
// hi_fan.go
package main
import (
"sync"
"time"
)
func producer(n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < n; i++ {
out <- i
}
}()
return out
}
func square(inCh <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range inCh {
out <- n * n
// simulate
time.Sleep(time.Second)
}
}()
return out
}
func merge(cs ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
collect := func(in <-chan int) {
defer wg.Done()
for n := range in {
out <- n
}
}
wg.Add(len(cs))
// FAN-IN
for _, c := range cs {
go collect(c)
}
// 错误方式:直接等待是bug,死锁,因为merge写了out,main却没有读
// wg.Wait()
// close(out)
// 正确方式
go func() {
wg.Wait()
close(out)
}()
return out
}
func main() {
in := producer(10)
// FAN-OUT
c1 := square(in)
c2 := square(in)
c3 := square(in)
// consumer
for _ = range merge(c1, c2, c3) {
}
}