duanleiming2014 2018-08-24 03:15
浏览 144
已采纳

Golang频道,执行顺序

I'm learning Go, and have run across the following code snippet:

package main

import "fmt"

func sum(a []int, c chan int) {
    sum := 0
    for _, v := range a {
        sum += v
    }
    c <- sum // send sum to c
}

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

    c := make(chan int, 2)
    go sum(a[0:3], c)
    go sum(a[3:6], c)
    x := <-c
    y := <-c
    // x, y := <-c, <-c // receive from c

    fmt.Println(x, y)
}

Output:

-5 17

Program exited.

Can someone please tell me why the 2nd calling of the "sum" function is coming through the channel before the 1st one? It seems to me that the output should be:

17 -5

I've also tested this with an un-buffered channel and it also gives the same order of output. What am I missing?

  • 写回答

3条回答 默认 最新

  • dth8312 2018-08-24 03:30
    关注

    You are calling the go routine in your code and you can't tell when the routine will end and the value will be passed to the buffered channel.

    As this code is asynchronous so whenever the routine will finish it will write the data to the channel and will be read on the other side. In the example above you are calling only two go routines so the behavior is certain and same output is generated somehow for most of the cases but when you will increase the go routines the output will not be same and the order will be different unless you make it synchronous.

    Example:

    package main
    
    import "fmt"
    
    func sum(a []int, c chan int) {
        sum := 0
        for _, v := range a {
            sum += v
        }
        c <- sum // send sum to c
    }
    
    func main() {
        a := []int{7, 2, 8, -9, 4, 2, 4, 2, 8, 2, 7, 2, 99, -32, 2, 12, 32, 44, 11, 63}
    
        c := make(chan int)
        for i := 0; i < len(a); i = i + 5 {
            go sum(a[i:i+5], c)
        }
        output := make([]int, 5)
        for i := 0; i < 4; i++ {
            output[i] = <-c
        }
        close(c)
    
        fmt.Println(output)
    }
    

    The output for this code on different sample runs was

    [12 18 0 78 162] 
    
    [162 78 12 0 18]
    
    [12 18 78 162 0]
    

    This is because the goroutines wrote the output asynchronously to the buffered channel.

    Hope this helps.

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

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题