dongshan8194 2019-08-29 09:56
浏览 96
已采纳

添加表达式“ fmt.Println()”时发生了什么

I`m a tiro about the golang and during the exploring the channel,I was comfused by following code ,so anyone who can tell me the differences between that?

when I run the code,the console logs -5,17 And if I make the comment use ,I get different result 17,-5 I don`t know what happend ...

golang version is the lastest one

//comman func
func sum(a []int, c chan int) {
    total := 0
    for _, v := range a {
        total += v
    }
    c <- total  // send total to c
}
func main (){
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    go sum(a[:len(a)/2], c)
        //fmt.Println(a[:len(a)/2])
    go sum(a[len(a)/2:], c)
        //fmt.Println(a[len(a)/2:])
    gh,w33 :=  <-c, <-c
    fmt.Println(gh,w33)
}

I expect the two times of results are 17,-5 ,but when the comment isn`t useful ,the result is -5 17

  • 写回答

1条回答 默认 最新

  • douzen1896 2019-08-30 07:43
    关注

    golang uses a scheduler to schedule go routines. You can read more about it here https://povilasv.me/go-scheduler/ So when you run the above program. It's not certain that that goroutines will be executed in the order that you have written.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)