14.12 Chaining goroutines 链式协程 (#628)

* Create 14.12.md

* Update 14.12.md

* Update 14.12.md
This commit is contained in:
Respawnz
2019-07-28 10:27:46 +08:00
committed by ᴊ. ᴄʜᴇɴ
parent 16cf646cfc
commit 120cb3dccd

42
eBook/14.12.md Normal file
View File

@@ -0,0 +1,42 @@
# 14.12 链式协程
下面的演示程序 [chaining.go](examples/chapter_14/chaining.go) 再次展示了启动巨量的Go协程是多么容易。这些协程已全部在 main 函数中的 for
循环里启动。当循环完成之后一个0被写入到最右边的通道里于是100,000个协程开始执行接着`1000000`这个结果会在1.5秒之内被打印出来。
这个程序同时也展示了如何通过`flag.Int`来解析命令行中的参数以指定协程数量,例如:`chaining -n=7000`会生成7000个协程。
[示例 14.17 - chaining.go](examples/chapter_14/chaining.go)
```go
package main
import (
"flag"
"fmt"
)
var ngoroutine = flag.Int("n", 100000, "how many goroutines")
func f(left, right chan int) { left <- 1 + <-right }
func main() {
flag.Parse()
leftmost := make(chan int)
var left, right chan int = nil, leftmost
for i := 0; i < *ngoroutine; i++ {
left, right = right, make(chan int)
go f(left, right)
}
right <- 0 // bang!
x := <-leftmost // wait for completion
fmt.Println(x) // 100000, ongeveer 1,5 s
}
```
## 链接
- [目录](directory.md)
- 上一节:[限制同时处理的请求数](14.11.md)
- 下一节:[在多核心上并行计算](14.13.md)