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

我有兴趣在 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


    }


翻过高山走不出你
浏览 201回答 1
1回答

猛跑小猪

您正在访问i所有 goroutine 中的相同副本。您看到的输出是因为循环恰好在任何 goroutine 开始执行之前完成。这意味着它i在所有 goroutine中具有相同的值,即它在循环中的最后一个值。i将参数作为参数传递给每个 goroutine,从而在每个 goroutine 上操作一个副本,解决了这个问题。您wg.Wait()在循环中添加时看到预期结果的原因是因为您随后引入了同步,在开始下一个 goroutine 之前等待 goroutine 完成。这意味着执行实际上是串行的,而不是并行的。这是更新后的代码,它按您的预期工作:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "runtime"&nbsp; &nbsp; "sync")func process_array(x, y int) int {&nbsp; &nbsp; r := x + y&nbsp; &nbsp; return r}func main() {&nbsp; &nbsp; a1 := []int{0, 1, 2, 3, 4}&nbsp; &nbsp; a2 := []int{10, 20, 30, 40, 50}&nbsp; &nbsp; runtime.GOMAXPROCS(8)&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; for i := 1; i < 4; i++ {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func(i int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x := process_array(a1[i], a2[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(a1[i], "+", a2[i], "=", x)&nbsp; &nbsp; &nbsp; &nbsp; }(i)&nbsp; &nbsp; &nbsp; &nbsp; //wg.Wait() give the good result&nbsp; &nbsp; &nbsp; &nbsp; //but it is not parallel processing&nbsp; &nbsp; &nbsp; &nbsp; // 1 + 20 = 21&nbsp; &nbsp; &nbsp; &nbsp; // 2 + 30 = 32&nbsp; &nbsp; &nbsp; &nbsp; // 3 + 40 = 43&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait() // give a repetition of the same result :&nbsp; &nbsp; // 4 + 50 = 54&nbsp; &nbsp; // 4 + 50 = 54&nbsp; &nbsp; // 4 + 50 = 54}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go