小编jwt*_*tnb的帖子

goroutines执行顺序

我正在尝试理解这段代码,不确定为什么第二轮在第一轮之前执行.如果有人能真正帮助我,那就太棒了!

func sum(a []int, c chan int) {
   fmt.Println("summing: ", a)
   total := 0
   for _, v := range a {
      total += v
   }
   //fmt.Println("send to c",total)
   c <- total  // send total to c
}
func main() {
    //a := []int{7, 2, 8,134,23,23,1,23,1234,143, -9, 4, 0, 1234}

    c := make(chan int)

    go sum([]int{1,2,3}, c)
    go sum([]int{4,5,6}, c)

    x := <-c
    fmt.Println(x)
    x = <-c
    fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

summing:  [4 5 6]
15
summing:  [1 2 3]
6
Run Code Online (Sandbox Code Playgroud)

go goroutine

4
推荐指数
1
解决办法
2645
查看次数

标签 统计

go ×1

goroutine ×1