亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
守著星空守著你 2022-12-26 10:15:52
在下面的示例中,為什么在“Bonjour”之前打印“Greetings done”?發送例程不應該等到接收例程收到通道中的值嗎?package mainimport (    "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 mainGreetings doneBonjourmain done發送例程不應該等到接收例程收到通道中的值嗎?意思是不應該在“Bonjour”之后打印“Greetings done”嗎?因為發送例程(問候語)將被阻塞,直到主例程收到它的值。
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

“Greetings done”和“Bonjour”之間沒有明確的順序。換句話說,它們可能以任何順序出現,并且這仍然是程序的有效行為。

不應該在“Bonjour”之后打印“Greetings done”嗎?因為發送例程(問候語)將被阻塞,直到主例程收到它的值。

在主 goroutine 接收到它的值之前,發送者將被阻塞是正確的。盡管如此,主 goroutine 必須在接收到值打印出來。

    // main routine will receive it and prints it
    fmt.Println(<-myChannel)

這個評論基本上是正確的,但僅僅因為它執行了 A 和 B(接收和打?。?,并不意味著 A 和 B 同時發生。它只是接收同步的值。



查看完整回答
反對 回復 2022-12-26
  • 1 回答
  • 0 關注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號