1 回答
TA贡献1801条经验 获得超16个赞
在这种情况下,您不需要使用 chan。
package main
import (
"fmt"
"sync"
"time"
)
func double(i int) int {
result := 2 * i
fmt.Println(result)
time.Sleep(500000000)
return result
}
func notParallel(arr []int) (outArr []int) {
for _, i := range arr {
outArr = append(outArr, double(i))
}
return
}
// how to do the same as notParallel func in parallel way.
// For each element of array double func should evaluate concuruntly
// without waiting each next element to eval
func parallel(arr []int) (outArr []int) {
outArr = make([]int, len(arr))
var wg sync.WaitGroup
for counter, number := range arr {
wg.Add(1)
go func(counter int, number int) {
outArr[counter] = double(number)
wg.Done()
}(counter, number)
}
wg.Wait()
return
}
func main() {
arr := []int{7, 8, 9}
fmt.Printf("%d\n", notParallel(arr))
fmt.Printf("%d\n", parallel(arr))
}
因为并行必须等待 goroutine(s) 的所有完成。
而且我注意到您的代码不工作,因为你是指counter,number在同样的功能范围。
- 1 回答
- 0 关注
- 180 浏览
添加回答
举报