簡體   English   中英

為 class 模板聲明用戶定義的 OpenMP 縮減

[英]Declare user-defined reduction of OpenMP for class template

使用 OpenMP 時,我想為 class 模板聲明用戶定義的縮減。

#include <omp.h>
#include <iostream>

template<typename T>
class Foo
{
  public:
  T Data_;

  template<typename U> friend Foo<U> operator+( const Foo<U>& lhs, const Foo<U>& rhs );
};

template<typename U>
Foo<U> operator+( const Foo<U>& lhs, const Foo<U>& rhs )
{
  Foo<U> Addition;

  Addition.Data_ = lhs.Data_ + rhs.Data_;

  return Addition;
}

#pragma omp declare reduction( + : template<typename U> Foo<U> : omp_out = omp_out + omp_in ) initializer (omp_priv=omp_orig)

int main( int argc, char* argv[] )
{
  Foo<int> Array[100];
  
  for ( int i = 0 ; i < 100 ; ++i )
  {
    Array[i].Data_ = i;
  }
  
  Foo<int> Sum {0};
  
  #pragma omp parallel for num_threads(4) reduction( + : Sum )
  for ( int i = 0 ; i < 100 ; ++i )
  {
    Sum.Data_ += Array[i].Data_;
  }
  
  std::cout << Sum.Data_ << std::endl;
  
  return 0;
}

但我收到以下錯誤:

error: expected type-specifier before 'template'
#pragma omp declare reduction( + : template<typename U> Foo<U> : omp_out = omp_out + omp_in ) initializer (omp_priv=omp_orig)
                                   ^~~~~~~~

我可以通過將template<typename U> Foo<U>替換為Foo<int>來修復錯誤。

但我想知道繼續使用template是否有任何解決方案。

謝謝。

假設您有一個模板化的 function

template<typename T>
T f(T x,T y) {};

您可以模板化減少:

#pragma omp declare reduction                                   \
  (rwzt:T:omp_out=f<T>(omp_out,omp_in))

並將其用作:

template<typename T>
T generic_reduction( vector<T> tdata ) {
  #pragma omp declare reduction                                   \
    (rwzt:T:omp_out=reduce_without_zero<T>(omp_out,omp_in))

  T tmin;
  #pragma omp parallel for reduction(rwzt:tmin)
   for ( stuff ) {}
  return tmin;
}

auto tm = generic_reduction<float>( /* some vector<float> */ );

這並不完全優雅,因為您必須使減少的聲明非常接近執行減少。 您需要定義一個 function 來包含它們也不優雅。 我想不出在調用環境中使用 lambda 的方法。

暫無
暫無

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

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