我有一个for循环,它迭代一个字符串映射作为键(keyString
(和一个类型为Data
(sliceValue
(的切片作为值。在循环中,我有一个函数process()
,它接受sliceValue
和keyString
并对其进行一些操作
我希望对所有切片并行执行process
函数。
我提到的代码是这样的:
for keyString, sliceValue := range mapWithKeyStringAndSliceValue {
result, err := process(keyString, sliceValue)
// some other code after this
}
如上所述,process
函数应该对所有sliceValue并行执行。
我看了这个问题想得到一些想法,但它有一个不同的操作要做。我是新的通道和去的程序,希望任何帮助!
使用sync.WaitGroup
并在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()