-
Notifications
You must be signed in to change notification settings - Fork 4
/
2.5.2-goroutine3.go
executable file
·59 lines (52 loc) · 1.03 KB
/
2.5.2-goroutine3.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
//++++++++++++++++++++++++++++++++++++++++
// 《Go语言高级开发与实战》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 知乎:https://www.zhihu.com/people/shirdonl
// 公众号:源码大数据
// 仓库地址:https://gitee.com/shirdonl/goAdvanced
// 仓库地址:https://github.com/shirdonl/goAdvanced
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"fmt"
)
//Pipeline 模式
func Generator(max int) <-chan int {
out := make(chan int, 100)
go func() {
for i := 1; i <= max; i++ {
out <- i
}
close(out)
}()
return out
}
func Power(in <-chan int) <-chan int {
out := make(chan int, 100)
go func() {
for v := range in {
out <- v * v
}
close(out)
}()
return out
}
func Sum(in <-chan int) <-chan int {
out := make(chan int, 100)
go func() {
var Sum int
for v := range in {
Sum += v
}
out <- Sum
close(out)
}()
return out
}
func main() {
// [1, 2, 3, 4, 5]
fmt.Println(<-Sum(Power(Generator(5))))
}
//55