加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang`select`似乎不公平

发布时间:2020-12-16 09:24:59 所属栏目:大数据 来源:网络整理
导读:参见英文答案 golang: How the select worked when multiple channel involved?????????????????????????????????????3个 我是Golang的初学者,我从官方 spec of select中读到,当更多的通信可以继续进行时,我会做统一的伪随机,但是当我尝试下面的代码时 packa
参见英文答案 > golang: How the select worked when multiple channel involved?????????????????????????????????????3个
我是Golang的初学者,我从官方 spec of select中读到,当更多的通信可以继续进行时,我会做统一的伪随机,但是当我尝试下面的代码时

package main

import (
    "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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读