英文:
Passing slice to function used for go routine
问题
你的代码中创建了四个goroutine来并行计算,但是它们似乎没有真正并行执行。这可能是因为你没有使用适当的并发控制机制来确保goroutine之间的并行执行。
在你的calculate函数中,你可以使用sync.WaitGroup来实现并发控制。首先,在函数开始时,创建一个WaitGroup对象,并将其计数器设置为goroutine的数量。然后,在每个goroutine的末尾,调用WaitGroup的Done()方法来减少计数器。最后,在所有goroutine创建完成后,调用WaitGroup的Wait()方法来等待所有goroutine完成。
下面是修改后的代码示例:
import "sync"
func calculate(slice_1 [][][array_size]int, slice_2 [][][array_size]int, coreCount int) {
var wg sync.WaitGroup
wg.Add(coreCount)
for k := 0; k < coreCount; k++ {
go func(k int) {
defer wg.Done()
for i := k; i < len(slice_1); i += coreCount {
// 在这里执行你的计算逻辑
}
}(k)
}
wg.Wait()
}
通过使用sync.WaitGroup,你可以确保所有的goroutine都完成后再继续执行后续的代码,从而实现并行计算。
英文:
I have the following function which takes as parameters two slices of two dimensional arrays of ints (where coreCount is amount of cores available)
func calculate(slice_1 [][array_size][array_size]int, slice_2 [] [array_size[array_size]int, coreCount int) {
//for each (coreCount*k + i, i = 0, ... , coreCount) matrix from slice_1 take matrix from slice_2 and check some criteria while not changing matrix under check
}
Slices are quite big in size (thousands of two dimensional arrays) so it's good idea to do the checking in parallel. So I simply create (in case of 4 cores compurer)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)
But it still calculates not in parallel. What's wrong?
答案1
得分: 1
在go
语句中不需要使用func
(只需写成go funcName(arg1, arg2)
)。
另外,我们需要整个程序(或者至少是一个简化的、可工作的版本)才能帮助你。你是否设置了GOMAXPROCS?
英文:
There's no need for func
in a go
statement (just write go funcName(arg1, arg2)
).
Also, we'll need the whole program (or at least a simplified, working version) to be able to help you. Have you set GOMAXPROCS?
答案2
得分: 1
为了并行进行一些检查,你的 goroutine 需要查看输入数据的不同部分。根据你简短的代码草图,最多你会同时运行相同的计算四次。当然,这是在假设你实际上使用相同的参数生成了四个 goroutine,并且没有任何区别它们的东西的情况下。
英文:
To do some checking in parallel, your goroutines would need to look at different parts of the input data and from your very brief code sketch, at best you'd run the same calculation four times. That is, of course, assuming that you actually spawn four goroutines with the same arguments and nothing to distinguish them from each other.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论