使用嵌套的OpenMP pragma时,为什么c ++ 11线程无法加入?

ill*_*umi 6 c++ multithreading openmp c++11

下面的代码应该非常简单,但在尝试使用嵌套的OpenMP代码对线程执行.join()时,似乎最终处于悬空状态.使用GCC编译器4.7.2与64位来自并行线程http://sourceforge.net/projects/mingwbuildsg++ 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;
}
Run Code Online (Sandbox Code Playgroud)

Hri*_*iev 7

混合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;
}
Run Code Online (Sandbox Code Playgroud)

omp_set_nested()需要调用才能启用默认禁用的嵌套并行操作.

  • QtThreads和C++ 11线程都是系统线程库的包装器,在大多数Unix系统上大多数都可能是"pthreads".GCC的OpenMP运行时也实现为`pthreads`的包装器.它可能适用于您的情况以及许多其他情况,但仍然是未定义的行为. (5认同)