如何在Go语言中并行调用函数

huangapple go评论85阅读模式
英文:

How to call a function in parallel in Go

问题

我正在尝试并行运行一个函数...当我这样做时,

func runParallel() {
    var out [5]chan string
    for i := range out {
        out[i] = make(chan string)
    }
    for j:=0; j<2; j++ {
        fmt.Println("\nStarting: ", j)
        go func() {
            out[0] <- f3(4)
        }()

        fmt.Println(<-out[0])
    }
}

func main() {    
    runParallel()
}

我发现函数被串行调用,一个接一个地进行...但是当我这样做时,

func runParallel() {
    var out [5]chan string
    for i := range out {
        out[i] = make(chan string)
    }

    fmt.Println("\nStarting: ", j)
    go func() {
        out[0] <- f3(4)
    }()
    go func() {
        out[0] <- f3(4)
    }()

    fmt.Println(<-out[0])
}

func main() {    
    runParallel()
}

函数被并行调用。

我需要在一个循环中并行调用该函数,请帮忙。

英文:

I am trying to run a function in parallel.... when I do it

func runParallel() {
    var out [5]chan string
    for i := range out {
        out[i] = make(chan string)
    }
    for j:=0; j&lt;2; j++ {
        fmt.Println(&quot;\nStarting: &quot;, j)
        go func() {
            out[0] &lt;- f3(4)
        }()

        fmt.Println(&lt;-out[0])
    }
}

func main() {    
    runParallel()
}

I see that function gets called serially one after the other... but when i do..

func runParallel() {
    var out [5]chan string
    for i := range out {
        out[i] = make(chan string)
    }

    fmt.Println(&quot;\nStarting: &quot;, j)
    go func() {
        out[0] &lt;- f3(4)
    }()
    go func() {
        out[0] &lt;- f3(4)
    }()

    fmt.Println(&lt;-out[0])
}

func main() {    
    runParallel()
}

The function gets called parallel.

I need to get the function called parallel in a for loop, Please help.

答案1

得分: 3

请记住,goroutine 提供了并发性,而并发性不等于并行性

你第一个示例中的问题是你在 for 循环内部从无缓冲通道中读取,因此在 goroutine 中进行的写入操作被序列化等待读取。将读取操作移到 for 循环外部,或者将读取操作放在它自己的 goroutine 中,你可能会看到更多的并行化。

英文:

Keep in mind that goroutines provide concurrency, and concurrency is not parallelism.

The problem in your first example is that you're reading from the unbuffered channel inside the for loop so the write that's happening in the goroutine is serialized waiting for the read. Move the read outside of the for loop, and/or put the read in it's own goroutine and you may see more parallelization.

huangapple
  • 本文由 发表于 2017年4月19日 00:38:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/43477725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定