在例程中执行的顺序

met*_*eto 1 concurrency go goroutine

我最近开始使用go,我对这个程序的执行顺序感到很困惑.我希望我不是在这里问一些非常微不足道的问题.

这在golang之旅基本上是#69,我插入了一些Println; 链接到游乐场:http://play.golang.org/p/PXDlD3EA2f

func fibonacci(c, quit chan int) {
    x, y := 0, 1

    fmt.Println("Inside the fibonacci")

    for {
        select {
        case c <- x:
            fmt.Println("Inside the for, first case, before reassigning ", x, y)
            x, y = y, x+y
            fmt.Println("Inside the for, first case, after reassigning ", x, y)
        case <-quit:
            fmt.Println("quit")
            return
        }
    }
}

func main() {
    fmt.Println("Begin of Main")
    c := make(chan int)
    quit := make(chan int)
    fmt.Println("Before gonig to the func")
    go func() {
        fmt.Println("Inside go routine")
        fmt.Println("Inside go routine... again")
        for i := 0; i < 10; i++ {
            fmt.Println("Inside go routine and the for, before printing the channel")
            fmt.Println(<-c)
        }
        quit <- 0
    }()
    fmt.Println("Before calling to fibonacci")
    fibonacci(c, quit)
    fmt.Println("Closing")
}
Run Code Online (Sandbox Code Playgroud)

在我获得的非常详细的输出中(见下图所示),有几件我不明白的事情:

  • 为什么"走进斐波那契"线在前往常规之前呢?这是因为在go命令之后,编译器只是在func和fibonacci内同时读取?

  • 斐波纳契和func如何相互作用?func没有改变通道c,为什么斐波那契反应?谁在换c?

  • 为什么在斐波那契里面每次都有5张照片?诚实我只期待2.

输出功能:

在此输入图像描述

One*_*One 5

让我们一步一步来:

*为什么"在斐波那契之内"线在前往常规之前?这是因为在go命令之后,编译器只是在func和fibonacci内同时读取?

因为你的go例程实际上是在你调用之后启动的fibonacci,所以调度程序需要一点时间来启动,例如,如果你启动一个调用goroutine fmt.Println并且什么都不做等待main,程序将在执行之前退出.

*斐波纳契和func如何相互作用?func没有改变通道c,为什么斐波那契反应?谁在换c?

fibonacci 将数字推入频道,注意这部分:

select {
        case c <- x: //this is sending x to the channel
Run Code Online (Sandbox Code Playgroud)

*为什么在fibonacci里面每次都有5张照片?诚实我只期待2.

这又取决于调度程序和fmt.Print*不锁定标准输出的事实,输出可以按任何顺序发生,因为它是2个不同的线程打印东西.