如果工作起作用,以下OMP如何平行?

发布于 2025-02-03 12:06:42 字数 709 浏览 2 评论 0原文

当我输入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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戴着白色围巾的女孩 2025-02-10 12:06:42

您看到的行为是正确的(假设变量TID已声明为私有,否则您在此处具有竞赛条件)。

实际上,如果(i)将创建一个并行区域,则仅当i不是0时
但是,如果创建了并行区域,则以下#pragma oppallel num_threads(5)将被忽略,因为默认情况下,禁用了嵌套的并行性。

如果i0,并且未创建第一个并行区域(这里不再是嵌套并行性),那么确实将创建第二个线程,并且将产生5个线程。

总而言之,i non null可防止要创建的内部并行区域,而i null允许它。

The behaviour you see is correct (assuming that the variable tid has been declared private 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 if i isn't 0.
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 was 0 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, while i null allows it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文