如果工作起作用,以下OMP如何平行?
当我输入i = 1时输出:
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
但是当我输入i = 0时,输出:
c[1] = 9
c[2] = 11
c[3] = 13
c[4] = 15
c[0] = 7
i = 0的输出不应该是i = 1的输出,反之亦然?
#include<omp.h>
#include<stdio.h>
int main(){
int a[5] = {1, 2, 3, 4, 5} ;
int b[5] = {6, 7, 8, 9, 10} ;
int c[5];
int tid;
int i;
scanf("%d", &i);
#pragma omp parallel if(i)
{
#pragma omp parallel num_threads(5)
{
tid = omp_get_thread_num();
c[tid] = a[tid] + b[tid];
printf("c[%d] = %d\n", tid, c[tid]);
}
}
}```
When I enter i = 1 it outputs:
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
but when i enter i = 0 it outputs:
c[1] = 9
c[2] = 11
c[3] = 13
c[4] = 15
c[0] = 7
shouldn't the output of i = 0 be the output of i = 1 and vice versa?
#include<omp.h>
#include<stdio.h>
int main(){
int a[5] = {1, 2, 3, 4, 5} ;
int b[5] = {6, 7, 8, 9, 10} ;
int c[5];
int tid;
int i;
scanf("%d", &i);
#pragma omp parallel if(i)
{
#pragma omp parallel num_threads(5)
{
tid = omp_get_thread_num();
c[tid] = a[tid] + b[tid];
printf("c[%d] = %d\n", tid, c[tid]);
}
}
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您看到的行为是正确的(假设变量
TID
已声明为私有
,否则您在此处具有竞赛条件)。实际上,如果(i)将创建一个并行区域,则仅当
i
不是0时
。但是,如果创建了并行区域,则以下
#pragma oppallel num_threads(5)
将被忽略,因为默认情况下,禁用了嵌套的并行性。如果
i
是0
,并且未创建第一个并行区域(这里不再是嵌套并行性),那么确实将创建第二个线程,并且将产生5个线程。总而言之,
i
non null可防止要创建的内部并行区域,而i
null允许它。The behaviour you see is correct (assuming that the variable
tid
has been declaredprivate
as otherwise you have a race condition here).Indeed, the first
#pragama omp parallel if(i)
will create a parallel region with an implementation defined number of threads if and only ifi
isn't0
.But then, if the parallel region has been created, then the following
#pragma omp parallel num_threads(5)
will be ignored as by default, nested parallelism is disabled.And if
i
was0
and the first parallel region wasn't created (no more nested parallelism here), then the second one will indeed be created and 5 threads will be spawned.In summary,
i
non null prevents the inner parallel region to be created, whilei
null allows it.