Files
the-way-to-go_ZH_CN/eBook/14.12.md
max-workspace 2476ea9806 采用斜体的形式完善译者注 (#733)
* 增加示例函数的注释

* 采用斜体完善注解内容
2019-10-31 23:11:28 -07:00

50 lines
1.6 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
}
```
*译者注原本认为leftmost的结果为1认为只在最初做了一次赋值实际结果为100000无缓存信道具有同步阻塞的特性*
*1.主线程的right <- 0right不是最初循环的那个right而是最终循环的right*
*2.for循环中最初的go f(left, right)因为没有发送者一直处于等待状态*
*3.当主线程的right <- 0执行时类似于递归函数在最内层产生返回值一般*
## 链接
- [目录](directory.md)
- 上一节:[限制同时处理的请求数](14.11.md)
- 下一节:[在多核心上并行计算](14.13.md)