使用 continue 作为中断替代方案的并行 OpenMP 循环
我指的是这个问题:带有break语句的并行OpenMP循环
代码这里建议:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(flag) continue;
if(element[i] ...)
{
...
flag=true;
}
}
使用继续
有什么优点?它比执行以下操作更快吗:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(!flag)
{
if(element[i] ...)
{
...
flag=true;
}
}
}
I'm referring to this question: Parallel OpenMP loop with break statement
The code suggested here:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(flag) continue;
if(element[i] ...)
{
...
flag=true;
}
}
What are the advantages of using continue
? Is it faster than doing the following:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(!flag)
{
if(element[i] ...)
{
...
flag=true;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译后,至少对于普通情况,它们是相同的。
不继续
与Continue
如果您比较生成的程序集,则两者之间没有区别。我冒昧地添加了一个2000年之前停止的垃圾条件。
After compilation, they are identical at least for the trivial case.
Without continue
With Continue
If you compare the resulting assembly there is no difference between the two. I have taken the liberty of adding a junk condition of halting before 2000.
正如@Niteya 所指出的,您使用哪一个并不重要,实际上它们是相同的。不过,我想指出的是,您的代码中存在竞争条件。根据 OpenMP 内存模型:
要纠正它,您必须使用原子读/写操作。所以,你的代码应该是这样的:
As pointed our by @Niteya it does not really matter which one you use, practically they are the same. I would like to point out, however, that you have a race condition in your code. According to OpenMP memory model:
To correct it you have to use atomic read/write operations. So, your code should be something like this: