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
}
- 1 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
