英文:
How to run a method inside for loop in parallel in go?
问题
我有一个for循环,它遍历一个以字符串为键(keyString
)和以Data
类型的切片(sliceValue
)为值的映射。在这个for循环内部,我有一个名为process()
的函数,它接受sliceValue
和keyString
并对其进行一些操作。
我希望process
函数能够并行地对所有切片执行。
我提到的代码如下所示:
for keyString, sliceValue := range mapWithKeyStringAndSliceValue {
result, err := process(keyString, sliceValue)
// 在此之后还有其他代码
}
如上所述,process
函数应该并行地对所有的sliceValue执行。
我查看了这个问题以获取一些思路,但它执行的操作有些不同。我对通道和Go协程还不太熟悉,希望能得到任何帮助!
英文:
I have a for loop which iterates over a map of a string as key (keyString
) and a slice of type Data
(sliceValue
) as values. Inside that for loop I have a function process()
that takes the sliceValue
and keyString
and does some operation on it.
I want the process
function to be executed in parallel for all slices.
The code that I am mentioning is like this:
for keyString, sliceValue := range mapWithKeyStringAndSliceValue {
result, err := process(keyString, sliceValue)
// some other code after this
}
As I mentioned above, the process
function should be executed in parallel for all the sliceValues.
I looked at this question to get some idea but it has a bit different operation to do. I am new to channel and go routines and would appreciate any help!
答案1
得分: 3
使用sync.WaitGroup
和在循环内部执行处理的方式来处理Go函数。
wg := new(sync.WaitGroup)
for keyString, sliceValue := range mapWithKeyStringAndSliceValue {
wg.Add(1)
// 将你的sliceValue类型替换为interface{}
go func(keyString string, sliceValue interface{}, wg *sync.WaitGroup) {
defer wg.Done()
result, err := process(keyString, sliceValue)
// 在此之后还有其他代码
}(keyString, sliceValue, wg)
}
wg.Wait()
英文:
Use sync.WaitGroup
and do process inside the loop in go func.
wg := new(sync.WaitGroup)
for keyString, sliceValue := range mapWithKeyStringAndSliceValue {
wg.Add(1)
// put your sliceValue type instead of interface{}
go func(keyString string, sliceValue interface{}, wg *sync.WaitGroup) {
defer wg.Done()
result, err := process(keyString, sliceValue)
// some other code after this
}(keyString, sliceValue, wg)
}
wg.Wait()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论