9 concurrency channel go goroutine
我是Go的新手,在理解并发和通道方面遇到了问题.
package main
import "fmt"
func display(msg string, c chan bool){
fmt.Println("display first message:", msg)
c <- true
}
func sum(c chan bool){
sum := 0
for i:=0; i < 10000000000; i++ {
sum++
}
fmt.Println(sum)
c <- true
}
func main(){
c := make(chan bool)
go display("hello", c)
go sum(c)
<-c
}
Run Code Online (Sandbox Code Playgroud)
该计划的输出是:
display first message: hello
10000000000
Run Code Online (Sandbox Code Playgroud)
但我认为它应该只有一行:
display first message: hello
Run Code Online (Sandbox Code Playgroud)
所以在main函数中,<-c阻塞它并等待另外两个rountines将数据发送到通道.一旦主函数从c接收数据,它就应该继续并退出.
显示和总和同时运行,总和需要更长时间,因此显示应该发送真实到c并且程序应该在总结完成之前退出...
我不确定我是否理解清楚.有人可以帮我吗?谢谢!
程序的确切输出未定义,取决于调度程序。调度器可以在当前未被阻塞的所有 goroutine 之间自由选择。它尝试通过在很短的时间间隔内切换当前的 goroutine 来同时运行这些 goroutine,以便用户感觉到一切都同时发生。除此之外,它还可以在不同的CPU上并行执行多个goroutine(如果你碰巧有一个多核系统并增加runtime.GOMAXPROCS)。可能导致输出的一种情况是:
main
创建两个 goroutinedisplay
display
打印出消息并被通道 send ( c <- true
) 阻塞,因为还没有接收者。sum
调度程序选择下一步运行sum
goroutine(它已经使用了相当长的时间)并继续display
display
将值发送到通道但这只是一种可能的执行顺序。还有很多其他的,其中一些会导致不同的输出。如果您只想打印第一个结果并随后退出程序,您可能应该使用 aresult chan string
并将main
函数更改为 print fmt.Println(<-result)
。