在下面的示例中,為什么在“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 同時發生。它只是接收同步的值。
- 1 回答
- 0 關注
- 92 瀏覽
添加回答
舉報
0/150
提交
取消