带有break语句的并行OpenMP循环 [英] Parallel OpenMP loop with break statement
问题描述
我知道您不能为OpenMP循环使用break语句,但是我想知道是否有任何变通办法,同时仍然可以从并行性中受益.基本上,我有一个"for"循环,该循环遍历一个大向量的元素,以寻找一个满足特定条件的元素.但是,只有一个元素可以满足条件,因此一旦找到,我们就可以跳出循环了,在此先感谢
I know that you cannot have a break statement for an OpenMP loop, but I was wondering if there is any workaround while still the benefiting from parallelism. Basically I have 'for' loop, that loops through the elements of a large vector looking for one element that satisfies a certain condition. However there is only one element that will satisfy the condition so once that is found we can break out of the loop, Thanks in advance
for(int i = 0; i <= 100000; ++i)
{
if(element[i] ...)
{
....
break;
}
}
推荐答案
您可以尝试使用while循环手动执行openmp for循环的操作:
You could try to manually do what the openmp for loop does, using a while loop:
const int N = 100000;
std::atomic<bool> go(true);
uint give = 0;
#pragma omp parallel
{
uint i, stop;
#pragma omp critical
{
i = give;
give += N/omp_get_num_threads();
stop = give;
if(omp_get_thread_num() == omp_get_num_threads()-1)
stop = N;
}
while(i < stop && go)
{
...
if(element[i]...)
{
go = false;
}
i++;
}
}
这样,您必须在每个循环中测试执行",但这没什么大不了的.更重要的是,这将对应于静态" omp for循环,仅当您可以期望所有迭代花费相似的时间时,此功能才有用.否则,可能已经完成了3个线程,而一个线程还有一半要完成...
This way you have to test "go" each cycle, but that should not matter that much. More important is that this would correspond to a "static" omp for loop, which is only useful if you can expect all iterations to take a similar amount of time. Otherwise, 3 threads may be already finished while one still has halfway to got...
这篇关于带有break语句的并行OpenMP循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!