簡體   English   中英

使靜態類成員在OpenMP中成為線程私有

[英]Making static class members threadprivate in OpenMP

我正在使用C ++中的OpenMP,並嘗試使一個class 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)

如果我使用Intel C ++編譯器,則代碼將編譯並運行。 當我搜索錯誤時,我已經發現了該問題的一些答案。

在C ++ STL類型的靜態實例上使用OpenMP threadprivate指令

但是,由於這是我要使用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的指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM