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条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误