英文:
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<2; j++ {
fmt.Println("\nStarting: ", j)
go func() {
out[0] <- f3(4)
}()
fmt.Println(<-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("\nStarting: ", j)
go func() {
out[0] <- f3(4)
}()
go func() {
out[0] <- f3(4)
}()
fmt.Println(<-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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论