Files
the-way-to-go_ZH_CN/eBook/14.12.md
2022-05-17 16:26:06 +08:00

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