我正在使用 C++ 中的 OpenMP 并尝试使类 threadprivate 的静态成员变量。 一个非常简化的示例代码示例如下所示
#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 编译器编译此代码,我会收到错误消息
threadprivatetest.cpp:8:27: 错误:'a' 尚未声明
#pragma omp threadprivate(a)
如果我使用英特尔 C++ 编译器,代码会编译并运行。 当我搜索错误时,我已经找到了这个问题的一些答案。
Using the OpenMP threadprivate directive on static instances of C++ STL types
然而,由于这是一个更大的项目,我想在其中使用 gcc 编译器,而且链接的帖子已经有 6 年了。 今天有没有可能用 gcc 编译器编译这样的代码? 有人可以详细解释旧帖子中提到的解决方法吗,因为我无法理解它?
感谢您的帮助!
最佳答案
下面的代码可以正常工作并完成我最初打算做的事情。
#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 的指针。
关于c++ - 在 OpenMP 中使静态类成员线程私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47475074/