mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 03:06:41 +08:00
Update 14.4.md
This commit is contained in:
@@ -84,6 +84,39 @@ Received on channel 2: 47404
|
|||||||
Received on channel 1: 94346
|
Received on channel 1: 94346
|
||||||
Received on channel 1: 94348
|
Received on channel 1: 94348
|
||||||
```
|
```
|
||||||
|
一秒内的输出非常惊人,如果我们给它计数(goroutine_select2.go),得到了90000个左右的数字。
|
||||||
|
|
||||||
|
##练习:
|
||||||
|
|
||||||
|
练习14.7:
|
||||||
|
* a)在练习5.4的for_loop.go中,有一个常见的for循环打印数字。在函数`tel`中实现一个for循环,用协程开始这个函数并在其中给通道发送数字。`main()`线程从通道中获取并打印。不要使用`time.Sleep()`来同步:[goroutine_panic.go](exercises/chapter_14/goroutine_panic.go)
|
||||||
|
* b)也许你的方案有效,可能会引发运行时的panic:`throw:all goroutines are asleep-deadlock!` 为什么会这样?你如何解决这个问题?[goroutine_close.go]((exercises/chapter_14/goroutine_close.go))
|
||||||
|
* c)解决a)的另外一种方式:使用一个额外的通道传递给协程,然后在结束的时候随便放点什么进去。`main()`线程检查是否有数据发送给了这个通道,如果有就停止:[goroutine_select.go](exercises/chapter_14/goroutine_select.go)
|
||||||
|
|
||||||
|
|
||||||
|
练习14.8:
|
||||||
|
|
||||||
|
从示例6.10的斐波那契程序开始,制定解决方案,使斐波那契周期计算独立到协程中,并可以把结果发送给通道。
|
||||||
|
|
||||||
|
结束的时候关闭通道。`main()`函数读取通道并打印结果:[goFibonacci.go](exercises/chapter_14/gofibonacci.go)
|
||||||
|
|
||||||
|
使用练习6.9中的算法写一个更短的[gofibonacci2.go](exercises/chapter_14/gofibonacci2.go)
|
||||||
|
|
||||||
|
使用`select`语句来写,并让通道退出([gofibonacci_select.go](exercises/chapter_14/gofibonacci_select.go))
|
||||||
|
|
||||||
|
注意:当给结果计时并和6.10对比时,我们发现使用通道通信的性能开销有轻微削减;这个例子中的算法使用协程并非性能最好的选择;但是[gofibonacci3](exercises/chapter_14/gofibonacci3.go)方案使用了2个协程带来了3倍的提速。
|
||||||
|
|
||||||
|
|
||||||
|
练习14.9:
|
||||||
|
|
||||||
|
做一个随机位生成器,程序可以提供无限的随机0或者1的序列:[random_bitgen.go](exercises/chapter_14/random_bitgen.go)
|
||||||
|
|
||||||
|
|
||||||
|
练习14.10:[polar_to_cartesian.go](exercises/chapter_14/polar_to_cartesian.go)
|
||||||
|
|
||||||
|
(这是一种综合练习,使用到章节4,9,11的内容和本章内容。)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 链接
|
## 链接
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user