在下面的示例中,为什么在“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”吗?因为发送例程(问候语)将被阻塞,直到主例程收到它的值。
米琪卡哇伊
为什么从 nil 通道读取会增加 Goroutines 的数量?
为什么在这个函数中使用通道?
getJSON()和getScript()有什么区别,为什么此例题中显示的是散步?
在面向对象中
相关分类