问题描述
我正在使用C ++中的OpenMP,并尝试使一个threadprivate类的静态成员变量.一个非常简化的示例代码示例如下所示:
I'm working with OpenMP in C++ and try to make a static member variable of a class threadprivate.A very simplified example code example looks like this
#include <omp.h>
#include<iostream>
template<class numtype>
class A {
public:
static numtype a;
#pragma omp threadprivate(a)
};
template<class numtype>
numtype A<numtype>::a=1;
int main() {
#pragma omp parallel
{
A<int>::a = omp_get_thread_num();
#pragma omp critical
{
std::cout << A<int>::a << std::endl;
}
} /* end of parallel region */
}
如果我尝试使用gcc编译器编译此代码,则会收到错误消息
If I try to compile this code with the gcc compiler I get the error message
threadprivatetest.cpp:8:27:错误:未声明'a'
threadprivatetest.cpp:8:27: error: ‘a’ has not been declared
#pragma omp threadprivate(a)
#pragma omp threadprivate(a)
如果使用Intel C ++编译器,则代码可以编译并运行.当我搜索错误时,我已经发现了该问题的一些答案.
The code compiles and runs if I use the Intel C++ compiler.When I searched for the error I already found that some answers to this problem.
使用OpenMP threadprivate指令C ++ STL类型的静态实例上
但是,因为这是我要使用gcc编译器的大型项目,并且链接的文章已经有6年的历史了.今天是否有可能用gcc编译器来编译此类代码?有人可以详细解释旧帖子中提到的解决方法,因为我听不懂吗?
However since this is for a larger project to where I want to use the gcc compiler and since the linked post is already 6 years old.Is there a possibility do compile such code with the gcc compiler today?Could somebody explain the work around mentioned in the old post in detail, because i wasn't able to understand it?
感谢您的帮助!
推荐答案
以下代码可以工作,并且可以完成我最初打算做的事情.
The following code works and does what I originally intended to do.
#include <omp.h>
#include<iostream>
template<class numtype>
class A {
public:
static numtype* a;
#pragma omp threadprivate(a)
};
template<class numtype>
numtype* A<numtype>::a=nullptr;
template class A<int>;
int main() {
#pragma omp parallel
{
A<int>::a = new int;
*A<int>::a = omp_get_thread_num();
#pragma omp critical
{
std::cout << *A<int>::a << std::endl;
}
} /* end of parallel region */
}
您可以看到不同之处在于,a现在是指向numtype的指针,而不是numtype.
As you can see the difference is that a is now a pointer to numtype instead of numtype.
这篇关于使静态类成员在OpenMP中成为线程私有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!