【发布时间】:2020-07-10 04:57:38
【问题描述】:
我是 Go 语言的新手,目前正在参加 Go 之旅。我对select 声明中的concurrency example 5 有疑问。
下面的代码已经用打印语句进行了编辑,以跟踪语句的执行。
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 0, 1
fmt.Printf("Run fib with c: %v, quit: %v\n", c, quit)
for {
select {
case c <- x:
fmt.Println("Run case: c<-x")
x, y = y, x+y
fmt.Printf("x: %v, y: %v\n", x, y)
case <-quit:
fmt.Println("Run case: quit")
fmt.Println("quit")
return
}
}
}
func runForLoop(c, quit chan int) {
fmt.Println("Run runForLoop()")
for i := 0; i < 10; i++ {
fmt.Printf("For loop with i: %v\n", i)
fmt.Printf("Returned from c: %v\n", <-c)
}
quit <- 0
}
func main() {
c := make(chan int)
quit := make(chan int)
go runForLoop(c, quit)
fibonacci(c, quit)
}
以下内容打印到控制台。
Run fib with c: 0xc00005e060, quit: 0xc00005e0c0
Run runForLoop()
For loop with i: 0
Returned from c: 0 // question 1
For loop with i: 1
Run case: c<-x // question 2
x: 1, y: 1
Run case: c<-x // question 2
x: 1, y: 2
Returned from c: 1
For loop with i: 2
Returned from c: 1
For loop with i: 3
// ...
我的问题是
-
- 这里收到的
c的值是0,即使没有执行任何选择块。我能否确认这是具有int类型的c变量的零值?
- 这里收到的
-
- 为什么 case
c<-x被执行了两次?
- 为什么 case
【问题讨论】:
标签: go concurrency