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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失