duanleiming2014 2018-08-23 19: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-23 19: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部