为什么在下面的 goroutines 和通道示例中

在下面的示例中,为什么在“Bonjour”之前打印“Greetings done”?发送例程不应该等到接收例程收到通道中的值吗?


package main


import (

    "fmt"

)


func greetings(c chan string) {

    fmt.Println(<-c)

    c <- "Bonjour"

    fmt.Println("Greetings done")

}


func main() {

    myChannel := make(chan string)


    // creates routine and leaves it upto Go to execute

    go greetings(myChannel)


    // while greetings() routine is getting executed, a new value is written to channel by main function

    myChannel <- "hi from main"

    // now main function (sender routine) is blocked. It wont proceed until another routine reads from the channel


    // By then greetings() routine will read the value and prints it. Hence "hi from main" gets printed


    // Now main function proceeds and moves to next line

    // simultaneously, greetings() would have written "Bonjour" to channel


    // main routine will receive it and prints it

    fmt.Println(<-myChannel)

    fmt.Println("main done")

}

该程序的输出是:

hi from main

Greetings done

Bonjour

main done


发送例程不应该等到接收例程收到通道中的值吗?意思是不应该在“Bonjour”之后打印“Greetings done”吗?因为发送例程(问候语)将被阻塞,直到主例程收到它的值。


守着星空守着你
浏览 76回答 1
1回答

米琪卡哇伊

“Greetings done”和“Bonjour”之间没有明确的顺序。换句话说,它们可能以任何顺序出现,并且这仍然是程序的有效行为。不应该在“Bonjour”之后打印“Greetings done”吗?因为发送例程(问候语)将被阻塞,直到主例程收到它的值。在主 goroutine 接收到它的值之前,发送者将被阻塞是正确的。尽管如此,主 goroutine 必须在接收到值后打印出来。&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;main&nbsp;routine&nbsp;will&nbsp;receive&nbsp;it&nbsp;and&nbsp;prints&nbsp;it &nbsp;&nbsp;&nbsp;&nbsp;fmt.Println(<-myChannel)这个评论基本上是正确的,但仅仅因为它执行了 A 和 B(接收和打印),并不意味着 A 和 B 同时发生。它只是接收同步的值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go