gpt4 book ai didi

go - channel slice 和并发函数执行

转载 作者:IT王子 更新时间:2023-10-29 02:05:36 24 4
gpt4 key购买 nike

如何在 slice 迭代中创建 channel slice 并同时运行函数 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))
}

playground

作为函数 double(i) 休眠 500 毫秒函数 notParallel(arr []int)arr []int 的 3 个元素工作 1500 毫秒 但函数 parallel(arr []int) 将工作大约 500 毫秒。

在我的实现中有错误...

panic: runtime error: index out of range

...在线...

chans[i] = make(chan int) // i = 0

最佳答案

在这种情况下,您不需要使用 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 完成。

我注意到您的代码不起作用,因为您在同一函数范围内引用了 counternumber

关于go - channel slice 和并发函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27812085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com