为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中并行处理数组会产生意想不到的结果

在 Go 中并行处理数组会产生意想不到的结果

Go
翻过高山走不出你 2021-12-27 10:48:12
我有兴趣在 Go 中并行计算相关性。我遇到的主要问题是所有 Go 进程似乎执行完全相同的计算。我在这里用一个非常简单的例子重现了这个问题。我获得: 4 + 50 = 54  4 + 50 = 54  4 + 50 = 54 代替 : 1 + 20 = 21  2 + 30 = 32  3 + 40 = 43 如果我向上移动“wg.Wait()”,我会得到很好的结果,但没有并行性 :( 提前感谢您的评论!   package main    import (        "fmt"        "runtime"        "sync"    )    func process_array(x, y int) int {      r := x + y      return r    }    func main() {        a1 := []int{0, 1, 2, 3, 4}        a2 := []int{10, 20, 30, 40, 50}        runtime.GOMAXPROCS(8)        var wg sync.WaitGroup        for i := 1; i < 4 ; i++ {            wg.Add(1)            go func() {                defer wg.Done()                x :=process_array(a1[i],a2[i])                fmt.Println(a1[i],"+", a2[i],"=", x)            }()            //wg.Wait() give the good result                         //but it is not parallel processing                        // 1 + 20 = 21                        // 2 + 30 = 32                        // 3 + 40 = 43          }        wg.Wait() // give a repetition of the same result :                  // 4 + 50 = 54                  // 4 + 50 = 54                  // 4 + 50 = 54    }
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

您正在访问i所有 goroutine 中的相同副本。您看到的输出是因为循环恰好在任何 goroutine 开始执行之前完成。


这意味着它i在所有 goroutine中具有相同的值,即它在循环中的最后一个值。


i将参数作为参数传递给每个 goroutine,从而在每个 goroutine 上操作一个副本,解决了这个问题。


您wg.Wait()在循环中添加时看到预期结果的原因是因为您随后引入了同步,在开始下一个 goroutine 之前等待 goroutine 完成。这意味着执行实际上是串行的,而不是并行的。


这是更新后的代码,它按您的预期工作:


package main


import (

    "fmt"

    "runtime"

    "sync"

)


func process_array(x, y int) int {

    r := x + y

    return r

}


func main() {

    a1 := []int{0, 1, 2, 3, 4}

    a2 := []int{10, 20, 30, 40, 50}


    runtime.GOMAXPROCS(8)

    var wg sync.WaitGroup


    for i := 1; i < 4; i++ {

        wg.Add(1)

        go func(i int) {

            defer wg.Done()

            x := process_array(a1[i], a2[i])

            fmt.Println(a1[i], "+", a2[i], "=", x)

        }(i)

        //wg.Wait() give the good result

        //but it is not parallel processing

        // 1 + 20 = 21

        // 2 + 30 = 32

        // 3 + 40 = 43

    }

    wg.Wait() // give a repetition of the same result :

    // 4 + 50 = 54

    // 4 + 50 = 54

    // 4 + 50 = 54


}


查看完整回答
反对 回复 2021-12-27
  • 1 回答
  • 0 关注
  • 200 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号