OpenMP标准仅考虑C++ 98(ISO/IEC 14882:1998).这意味着在C++ 03甚至C++ 11下没有标准的OpenMP支持用法.因此,任何使用C++> 98和OpenMP的程序都在标准之外运行,这意味着即使它在某些条件下工作,它也不太可能是可移植的,但绝对不能保证.
C++ 11具有自己的多线程支持,情况更糟,这很可能会在某些实现中与OpenMP发生冲突.
那么,将OpenMP与C++ 03和C++ 11一起使用有多安全?
可以安全地在一个相同的程序中使用C++ 11多线程和OpenMP但不交错它们(即在任何代码中没有传递给C++ 11并发特性的OpenMP语句,并且线程中没有C++ 11并发由OpenMP产生)?
我特别感兴趣的是我首先使用OpenMP调用一些代码,然后在相同的数据结构上使用C++ 11并发代码调用其他代码.
在以下示例中,C++ 11线程执行大约需要50秒,但OMP线程仅需5秒.有什么想法吗?(我可以向你保证,如果你正在做真正的工作而不是doNothing,或者如果你以不同的顺序进行,那么它仍然适用.)我也在16核机器上.
#include <iostream>
#include <omp.h>
#include <chrono>
#include <vector>
#include <thread>
using namespace std;
void doNothing() {}
int run(int algorithmToRun)
{
auto startTime = std::chrono::system_clock::now();
for(int j=1; j<100000; ++j)
{
if(algorithmToRun == 1)
{
vector<thread> threads;
for(int i=0; i<16; i++)
{
threads.push_back(thread(doNothing));
}
for(auto& thread : threads) thread.join();
}
else if(algorithmToRun == 2)
{
#pragma omp parallel for num_threads(16)
for(unsigned i=0; i<16; i++)
{
doNothing();
}
}
}
auto endTime = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = endTime - …Run Code Online (Sandbox Code Playgroud) 下面的代码应该非常简单,但在尝试使用嵌套的OpenMP代码对线程执行.join()时,似乎最终处于悬空状态.使用GCC编译器4.7.2与64位来自并行线程http://sourceforge.net/projects/mingwbuilds与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 …Run Code Online (Sandbox Code Playgroud)