简体   繁体   English

OpenMP在函数内部并行化循环

[英]OpenMP parallelize for loop inside a function

I am trying to parallelize this for loop inside a function using OpenMP, but when I compile the code I still have an error =( 我正在尝试使用OpenMP在函数内部并行化此for循环,但是当我编译代码时,我仍然遇到错误=(

Error 1 error C3010: 'return' : jump out of OpenMP structured block not allowed. 错误1错误C3010:“返回”:不允许跳出OpenMP结构化块。

I am using Visual studio 2010 C++ compiler. 我正在使用Visual Studio 2010 C ++编译器。 Can anyone help me? 谁能帮我? I appreciate any advice. 我感谢任何建议。

int match(char* pattern, int patternSize, char* string, int startFrom, unsigned int &comparisons) {
    comparisons = 0;
#pragma omp for 
    for (int i = 0; i < patternSize; i++){
        comparisons++;
        if (pattern[i] != string[i + startFrom])
            return 0;
    }
    return 1;
}

As @Hristo has already mentioned, you are not allowed to branch out of a parallel region in OpenMP. 正如@Hristo已经提到的那样,不允许您在OpenMP中分支到并行区域之外。 Among other reasons, this is not allowed because the compiler cannot know a priori how many iterations each thread should work on when it splits up a for loop like the one that you have written among the different threads. 除其他原因外,这是不允许的,因为编译器无法先验地知道每个线程在拆分for循环(例如您在不同线程之间编写的循环)时应进行多少次迭代。

Furthermore, even if you could branch out of your loop, you should be able to see that comparisons would be computed incorrectly. 此外,即使您可以跳出循环,您也应该能够看到comparisons计算不正确。 As is, you have an inherently serial algorithm that breaks at the first different character. 照原样,您有一个固有的串行算法,该算法在第一个不同的字符处中断。 How could you split up this work such that throwing more threads at this algorithm possibly makes it faster? 您如何拆分这项工作,以便在此算法上抛出更多线程可能使其更快?

Finally, note that there is very little work being done in this loop anyway. 最后,请注意,在此循环中几乎没有完成任何工作。 You would be very unlikely to see any benefit from OpenMP even if you could rewrite this algorithm into a parallel algorithm. 即使您可以将此算法重写为并行算法,也很难从OpenMP中获得任何好处。 My suggestion: drop OpenMP from this loop and look to implement it somewhere else (either at a higher level - maybe you call this method on different strings? - or in a section of your code that does more work). 我的建议是:从此循环中删除OpenMP,并寻求在其他地方实现它(在更高级别上-也许您在不同的字符串上调用此方法?-或在代码中执行更多工作的部分中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM