通道切片和并发函数执行

如何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


慕勒3428872
浏览 181回答 1
1回答

侃侃尔雅

在这种情况下,您不需要使用 chan。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func double(i int) int {&nbsp; &nbsp; result := 2 * i&nbsp; &nbsp; fmt.Println(result)&nbsp; &nbsp; time.Sleep(500000000)&nbsp; &nbsp; return result}func notParallel(arr []int) (outArr []int) {&nbsp; &nbsp; for _, i := range arr {&nbsp; &nbsp; &nbsp; &nbsp; outArr = append(outArr, double(i))&nbsp; &nbsp; }&nbsp; &nbsp; 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 evalfunc parallel(arr []int) (outArr []int) {&nbsp; &nbsp; outArr = make([]int, len(arr))&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; for counter, number := range arr {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func(counter int, number int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outArr[counter] = double(number)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; }(counter, number)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; return}func main() {&nbsp; &nbsp; arr := []int{7, 8, 9}&nbsp; &nbsp; fmt.Printf("%d\n", notParallel(arr))&nbsp; &nbsp; fmt.Printf("%d\n", parallel(arr))}因为并行必须等待 goroutine(s) 的所有完成。而且我注意到您的代码不工作,因为你是指counter,number在同样的功能范围。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go