douwen9343 2016-03-06 23:11
浏览 22

为什么在进行并行处理时可以在Go中重用通道?

Here is a code snippet from the official tutorial

package main

import "fmt"

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

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

    c := make(chan int)
    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    x, y := <-c, <-c // receive from c

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

Since we are doing the calculation in parallel, and each thread saves its result into the same channel, doesn't this screw up the data?

  • 写回答

2条回答 默认 最新

  • douba6361 2016-03-06 23:29
    关注

    It's true that when you send two values over a channel from two different goroutines that the ordering is not necessarily guaranteed (unless you've done something else to coordinate their sends).

    However, in this example, the ordering doesn't matter at all. Two values are being sent on the channel: the sum of the first half and the sum of the second.

    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    

    Since the only thing those two values are used for is to calculate the total sum, the order doesn't matter at all. In fact, if you ran the example enough times you should see that x and y are often swapped, but the sum x+y is always the same.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?