【问题标题】:OpenMP while loop inside parallelOpenMP while 循环内并行
【发布时间】:2016-03-19 16:11:16
【问题描述】:

//

编辑:我如何让 5 个线程同时运行代码 A 和第 6 个线程运行代码 B,然后在所有线程都有它们的代码后将它们的结果传递给单个线程?我读到我不允许使用关键字屏障OpenMP threads "disobey" omp barrier

这是我的原始代码

omp_set_num_threads(6);
#pragma omp parallel
    {
        int TID = omp_get_thread_num();

        while (true)
        {
            if (TID < 5)
            {
                // codeA

            }

            else
            {
                // codeB
            }

            // combine result from A and B
            #pragma single
            {
                //show result A and B
            }
        }
    }

我在谷歌上搜索了足够多的 Can I assign multiple threads to a code section in OpenMP? 后可能找到了解决方案

我应该能够设置 5 个线程来执行任务 A 和 1 个线程来执行任务 B。我只需要在退出 5 个线程以累积结果之前使用关键。

【问题讨论】:

  • 请避免多次问同一个问题。如果你想让your initial question 更清晰,只需编辑它。

标签: multithreading openmp


【解决方案1】:

以下代码是否举例说明了您要实现的内容?在这种特殊情况下,线程 0-4 只是将它们的线程标识符加 1 累加到 Aresult 中(并且由于它是一个共享变量,我们需要对它进行原子访问),而线程 5 只是将其线程标识符分配给 Bresult . 顺便说一句:你错过了#pragma omp single 中的 omp。

请注意,我在显示 A 和 B 的结果之间添加了几个#pragma omp barrier,以防止线程更改在 Aresult/Bresult 中计算的值。如果我们不添加屏障并且任何未通过#pragma omp single 的线程开始进行下一次迭代,则可能会发生这种情况。

请注意,添加障碍是可能的,因为在OpenMP threads "disobey" omp barrier 状态中接受的答案

来自 OpenMP V3.0/第 2.5 节工作共享结构:

以下限制适用于工作共享结构:

团队中的所有线程都必须遇到每个工作共享区域 或者根本没有。工作共享区域和障碍的顺序 团队中每个线程遇到的区域必须相同。

在这种情况下,每个线程在输入显示结果的代码之前和之后都会遇到障碍。

#include <omp.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    int Aresult = 0;
    int Bresult = 0;

    omp_set_num_threads(6);
    #pragma omp parallel
    {
        int TID = omp_get_thread_num();

        while (1 == 1)
        {
            if (TID < 5)
            {
                // codeA
                #pragma omp atomic
                Aresult += TID + 1; // Aresult should be 1+2+3+4+5
            }
            else
            {
                // codeB
                Bresult = TID;
            }

            #pragma omp barrier

            // combine result from A and B
            #pragma omp single
            {
                //show result A and B
                printf ("Aresult = %d Bresult = %d\n", Aresult, Bresult);

                // set Aresult & Bresult to 0 for next iteration
                Aresult = Bresult = 0;
            }

            #pragma omp barrier
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多