Files
the-way-to-go_ZH_CN/eBook/14.12.md
Respawnz 120cb3dccd 14.12 Chaining goroutines 链式协程 (#628)
* Create 14.12.md

* Update 14.12.md

* Update 14.12.md
2019-07-27 19:27:46 -07:00

43 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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)