【问题标题】:what happended when I add the expression "fmt.Println()"当我添加表达式“fmt.Println()”时发生了什么
【发布时间】:2020-01-02 13:57:44
【问题描述】:

我是 golang 的 tiro,在探索频道的过程中,我对以下代码感到困惑,所以谁能告诉我它们之间的区别?

当我运行代码时,控制台记录 -5,17 如果我使用评论,我会得到不同的结果 17,-5 我不知道发生了什么...

golang版本是最新的

//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)
}

我预计两次结果是 17,-5 ,但是当评论没有用时,结果是 -5 17

【问题讨论】:

  • goroutines 的执行顺序是不确定的(即随机的),没有同步。

标签: go channel


【解决方案1】:

golang 使用调度器来调度 go 例程。 你可以在这里阅读更多关于它的信息https://povilasv.me/go-scheduler/ 所以当你运行上面的程序时。不确定 goroutine 是否会按照您编写的顺序执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2018-06-07
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多