切片通道和并发功能执行

时间:2015-01-07 03:43:48

标签: go goroutine

如何创建切片通道并在切片迭代内同时运行函数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

1 个答案:

答案 0 :(得分:2)

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