Making static class members threadprivate in OpenMP

匆匆过客 提交于 2019-12-24 07:49:52

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/47475074/making-static-class-members-threadprivate-in-openmp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!