如何在Go语言中并行运行for循环内的方法?

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

How to run a method inside for loop in parallel in go?

问题

我有一个for循环,它遍历一个以字符串为键(keyString)和以Data类型的切片(sliceValue)为值的映射。在这个for循环内部,我有一个名为process()的函数,它接受sliceValuekeyString并对其进行一些操作。

我希望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()

huangapple
  • 本文由 发表于 2021年6月7日 20:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/67871953.html
匿名

发表评论

匿名网友

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

确定