c++ - 为什么在使用嵌套的 OpenMP pragma 时 c++11 线程变得不可连接?

标签 c++ multithreading c++11 openmp

以下代码应该非常简单,但在尝试使用嵌套的 OpenMP 代码在线程上执行 .join() 时,似乎最终陷入了挂起状态。使用 GCC 编译器 4.7.2 x64 和来自 http://sourceforge.net/projects/mingwbuilds 的 pthreads使用 g++ threadexample.cpp -Wall -std=c++11 -fopenmp -o threads

// threadexample.cpp
#include <iostream>
#include <thread>
#include <omp.h>

using namespace std;

void hello(int a) {

    #pragma omp parallel for
        for (int i=0;i<5;++i) {
            #pragma omp critical
            cout << "Hello from " << a << "! " << "OMP thread iter " << i << endl;
        }

    cout << "About to return from hello function" << endl;
}

int main (int argc, char ** argv) {

    thread t1(hello, 1); //fork
    cout << "t1 away!" << endl;
    thread t2(hello, 2);
    cout << "t2 away!" << endl;

    t1.join(); //join
    cout << "thread 1 joined" << endl;
    t2.join();
    cout << "thread 2 joined" << endl;

    return 0;
}

最佳答案

混合使用 OpenMP 和任何其他线程库(pthreads、Win32 线程等)可能不是一个好主意。 OpenMP 运行时的编写可能假设它完全控制线程并且可能不支持同时运行的parallel 区域(例如,它可能使用像信号量这样的全局变量来控制线程池) .

实现此目的的更好的纯 OpenMP 方法是:

#include <iostream>
#include <omp.h>

using namespace std;

void hello(int a) {

    #pragma omp parallel for
    for (int i=0;i<5;++i) {
        #pragma omp critical
        cout << "Hello from " << a << "! " << "OMP thread iter " << i << endl;
    }

    cout << "About to return from hello function" << endl;
}

int main (int argc, char ** argv) {

    omp_set_nested(1);

    #pragma omp parallel sections num_threads(2)
    {
       #pragma omp section
       {
           hello(1);
       }
       #pragma omp section
       {
           hello(2);
       }
    }

    return 0;
}

需要调用 omp_set_nested() 以启用默认情况下禁用的嵌套并行性。

关于c++ - 为什么在使用嵌套的 OpenMP pragma 时 c++11 线程变得不可连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197510/

相关文章:

c++ - 我可以在 std::list 中移动元素而不会使迭代器或引用失效,但是如何呢?

c++ - 结构数组和新建/删除

c++ - C++ 模块系统中如何处理模板?

java - 多线程java中的一进一出要求与统一服务员要求

Java谜题: busy wait threads stop working

c++ - 错误 : no match for ‘operator[]’ (operand types are ‘QVector<int>’ and ‘QCharRef’ )

c++ - 在 Excel 中关闭对 dll 的访问

c# - 使用闭包而不是共享状态锁的优点和缺点是什么?

c++ - 函数指针的现代 C++ 替代品

c++11 - 为什么我不能将 `new [ ]` 与智能指针一起使用?