Go-Select语句示例之旅

Go-Select语句示例之旅,go,concurrency,Go,Concurrency,我是围棋语言的新手,目前正在进行围棋之旅。我对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 {

我是围棋语言的新手,目前正在进行围棋之旅。我对
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)
}
主程序包
输入“fmt”
func-fibonacci(c,int){
x、 y:=0,1
fmt.Printf(“用c运行fib:%v,退出:%v\n”,c,退出)
为了{
挑选{

案例c对于1:它打印了Hi Burak的结果,感谢您的回复。对于1:如果选择cFor 2的案例:我理解c@quattad-对于1:如果选择了c@quattad对于1:两个goroutine之间没有执行顺序保证。另一个goroutine可以随时抢占正在运行的goroutine,在这种情况下,它以前就抢占了它可以打印output@quattad#2是相同的原因。当一个goroutine写入通道时,另一个goroutine读取它,此时,两个goroutine都被启用。它们可以以任何顺序执行。
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
...