此问题特定于OpenMP 3.0中的任务构造及其对C++隐式firstprivate的使用。我正在寻找对问题的解释和可能的解决方案。通过Openmp任务访问实例变量(隐式firstprivate)时发生分段错误
我对我正在处理的程序有一些分段错误;我设法将问题简化为以下测试用例。
的问题的发生是因为我从内的#pragma omp task
#include <iostream>
#include <omp.h>
using namespace std;
class A {
private:
int someInstanceVariable;
public:
// This is never called
A(int _someInstanceVariable) {
someInstanceVariable = _someInstanceVariable;
}
A(const A& _A) {
cout << "Copy constructor called" << endl;
someInstanceVariable = _A.someInstanceVariable;
}
void simpleTask() {
// This task makes a reference to someInstanceVariable in the current object
#pragma omp task
{
// For access to stdout
#pragma omp critical
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// This line uses someInstanceVariable and causes a segfault
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
cout << "The value of the someInstanceVariable = " << someInstanceVariable << endl;
}
}
}
};
int main(int argc, char* argv[]) {
#pragma omp parallel
{
#pragma omp single
{
for(int i = 0; i < 10; i++) {
A* temp = new A(i);
temp->simpleTask();
}
}
}
return 0;
}
访问实例变量(对象A的)当我编译并用gcc 4.5或更高(版本支持任务功能运行的程序在OpenMP中),即gcc -fopenmp myprogram.cpp
它运行良好。但是,当我使用英特尔的C++编译器(也支持任务功能的版本)编译和运行该程序时,例如icpc -openmp myprogram.cpp
它会出现段错误。
GCC的输出:
The value of the someInstanceVariable = 0
The value of the someInstanceVariable = 1
...
ICPC的输出:
Segmentation fault
我假设,其中至少有一个必须是错误的。我的具体问题:
- 什么是导致问题的原因?是否因为我在
#pragma omp task
中使用了someInstanceVariable
,并且它正在引发对此指针的隐式firstprivate引用? - 更好的是,有人能指出我在OpenMP 3.0 spec的具体部分谈到这个?
我知道,我可以通过创建一个局部变量解决问题
void simpleTask() { // This task makes a reference to someInstanceVariable in the current object #pragma omp task { int tempVariable = this -> someInstanceVariable; // For access to stdout #pragma omp critical { cout << "The value of the someInstanceVariable = " << tempVariable << endl; } } }
是否存在而无需创建一个临时变量别的办法吗?
请问您可以指向相关部分,指定术语“变量”的定义吗?我能找到类对象描述的最接近的部分是第93页上的第2.9.3.4节,它表示“变量作为另一个变量的一部分(作为结构数组)不能出现在firstprivate子句中”。但是,因为我没有明确指定任何带firstprivate子句的东西,所以编译器会自动处理引用(虽然看起来错了)。为什么编译器没有发出错误信号而不是继续处理?还有什么我误解的吗? – vazexqi
@vazexqi我目前正在处理类似的问题。你能分享一下你对这个问题的解释吗?我仍然不清楚如何处理openMP中的类对象。 – Callahan