我是Golang的初学者,我从官方 spec of select中读到,当更多的通信可以继续进行时,我会做统一的伪随机,但是当我尝试下面的代码时
package mainimport ( "fmt")func main() { // For our example we'll select across two channels. c1 := make(chan string) c2 := make(chan string) go func() { for { c1 <- "one" } }() go func() { for { c2 <- "two" } }() for i := 0; i < 100; i++ { select { case msg1 := <-c1: fmt.Println("received",msg1) case msg2 := <-c2: fmt.Println("received",msg2) } }}
它总是打印’收到两个’,似乎不是随机的结果,所以我在哪里错了?
代码可以是测试here.
解决方法 问题是你在go playground上运行它,在Go Playground上,GOMAXPROCS是1,这意味着一次执行一个goroutine,如果goroutine没有阻塞,调度程序不会被迫切换到其他goroutine.因此,您应该在本地计算机上运行它,以查看实际结果
总结When you run it locally,most likely GOMAXPROCS will be greater than 1 as it defaults to the number of cpu cores available (since Go 1.5). So it doesn’t matter if you have a goroutine executing an endless loop,another goroutine will be executed simultaneously,which will be the main(),and when main() returns,your program terminates; it does not wait for other non-main goroutines to complete
以上是内存溢出为你收集整理的Golang`select`似乎不公平全部内容,希望文章能够帮你解决Golang`select`似乎不公平所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)