dtf24224 2017-10-09 06:54
浏览 60
已采纳

同一频道中的两个goroutine-如何执行?

When I take the tour of Golang from golang.org, there's one code snippet I don't understand:

func sum(a []int, c chan int, order int) {
    sum := 0
    for _, v := range a {
        sum += v
    }
    fmt.Println(order, a)
    c <- sum // 将和送入 c
}

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    a1, a2 := a[:len(a)/2], a[len(a)/2:]

    go sum(a1, c, 1)
    x := <-c
    go sum(a2, c, 2)
    y := <-c
    //x := <-c
    //y := <-c
    // x, y := <-c, <-c // 从 c 中获取

    fmt.Println(x, y, x+y)
}

This is the output I expected:

1 [7 2 8]
2 [-9 4 0]
17 -5 12

and when I changed the code:

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    a1, a2 := a[:len(a)/2], a[len(a)/2:]

    go sum(a1, c, 1)
    //x := <-c
    go sum(a2, c, 2)
    //y := <-c
    x := <-c
    y := <-c
    // x, y := <-c, <-c // 从 c 中获取

    fmt.Println(x, y, x+y)
}

Why is the output like this:

2 [-9 4 0] 
1 [7 2 8]
-5 17 12
  • 写回答

2条回答 默认 最新

  • dongshen7407 2017-10-09 08:41
    关注

    the thing is u've missed the concept of concurrency there is no guarantee in executing functions in exact order of calling them with go

    the reason first code snippet works orderly is the x := <-c part this line force your app to wait until c channel is filled with data so second goroutine wont be called

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大