Reputation: 31
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 */
}
If I try to compile this code with the gcc compiler I get the error message
threadprivatetest.cpp:8:27: error: ‘a’ has not been declared
#pragma omp threadprivate(a)
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.
Using the OpenMP threadprivate directive on static instances of C++ STL types
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?
Thanks for your help!
Upvotes: 1
Views: 1047
Reputation: 31
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 */
}
As you can see the difference is that a is now a pointer to numtype instead of numtype.
Upvotes: 2