如何double(i)在切片迭代中同时创建通道切片和运行函数:
package main
import (
"fmt"
"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) {
var chans []chan int
for i := 0; i < len(arr); i++ {
chans[i] = make(chan int) // i = 0 : panic: runtime error: index out of range
}
for counter, number := range arr {
go func() {
chans[counter] <- double(number)
}()
}
return
}
func main() {
arr := []int{7, 8, 9}
fmt.Printf("%d\n", notParallel(arr))
fmt.Printf("%d\n", parallel(arr))
}
操场
由于函数double(i)休眠 500 毫秒,函数notParallel(arr []int)对 3 个元素的工作时间为 1500 毫秒,arr []int但函数parallel(arr []int)将工作约 500 毫秒。
在我的实现中有错误...
panic: runtime error: index out of range
... 在线的 ...
chans[i] = make(chan int) // i = 0
侃侃尔雅
相关分类