c++ - 在 OpenMP 中使静态类成员线程私有(private)

标签 c++ static openmp private

我正在使用 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/

相关文章:

c# - 在 ASP.NET 中使用静态变量代替应用程序状态

c# - 我怎么知道一个类是否可以用作静态类?

c - OpenMP:并行程序并不比串行程序快(或不是非常快)。我究竟做错了什么?

c++ - 为什么 OpenMP 程序只在一个线程中运行

c++ - 如何从 std::async 任务返回 std::tuple

c++ - 包含在许多翻译单元中时静态常量的开销?

C++14遇到奇怪的 "use of deleted function"错误

tomcat - 使用 Struts2 提供静态内容 : Tomcat error 404

c++ - 从 vector C++ 中获取方矩阵的行数和列数

c - C 语言 OpenMP 基准测试