我是围棋语言新手,目前正在进行围棋巡回赛。关于并发示例5 on select语句,我有一个问题。
下面的代码是用print语句编辑的,以跟踪语句的执行情况。
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,尽管没有执行任何select块。我能确认这是具有c类型的int变量的零值吗?c<-x被执行了两次?发布于 2020-07-10 05:09:10
对于1:它打印<-c的结果,这将阻塞,直到另一个goroutine写到它。因此,您的语句是不正确的:c<-x的select大小写与x=0一起运行。它不是chan变量的零值。如果通道关闭,或者使用通道的两个值形式read:value,ok := <-c,则只能从通道读取chan类型的零值。当ok=false时,value是通道值类型的零值.
对于2:c<-x将执行10次,因为您在For -循环中从它读取了10次,然后才写到quit,这将启用选择的第二种情况。您在这里看到的是循环的第二次迭代。
https://stackoverflow.com/questions/62827577
复制相似问题