Go-select来实现fibonacci数列

Go-select来实现fibonacci数列

 1 //fibonacco 1 1 2 3 5 8 前两个数相加等于后一个数
 2 
 3 package main
 4 
 5 import "fmt"
 6 
 7 //ch只写,quit只读
 8 func fibonacci(ch chan<- int, quit <-chan bool) {
 9     x, y := 1, 1
10 
11     for {
12         select {
13         case ch <- x:
14             x, y = y, x+y
15         case flag := <-quit:
16             fmt.Println("flag=", flag)
17             return
18         }
19     }
20 
21 }
22 
23 func main() {
24     ch := make(chan int)
25     quit := make(chan bool)
26 
27     //消费者,从channel读取内容
28     go func() {
29         for i := 0; i < 8; i++ {
30             num := <-ch
31             fmt.Println(num)
32         }
33         //可以停止
34         quit <- true
35     }() //别忘了()
36     //生产者, 产生数字,写入channel
37     fibonacci(ch, quit)
38 }
View Code

 

posted @ 2019-05-29 22:36  大西瓜Paul  阅读(124)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/