共用方式為


如何:轉換使用削減變數的 OpenMP 迴圈來使用並行執行階段

這個範例示範如何將使用 reduction 子句的 OpenMP parallel for 迴圈,轉換為使用並行執行階段。

OpenMP reduction 子句可讓您在平行區域末端指定一個或多個執行削減作業的執行緒私用變數。 OpenMP 預先定義一組削減運算子。 每個削減變數都必須是純量 (例如 int、long 和 float)。 OpenMP 也定義平行區域中削減變數用法的數個限制。

平行模式程式庫 (PPL) 提供了 concurrency::combinable 類別,這個類別提供可重複使用的執行緒區域儲存區,可讓您執行細部計算,然後將這些計算合併成最終的結果。 combinable 類別是作用於純量和複雜型別的範本。 若要使用 combinable 類別,請在平行建構主體中執行子運算,然後呼叫 concurrency::combinable::combineconcurrency::combinable::combine_each 方法產生最終的結果。 每個 combinecombine_each 方法都會接受「Combine 函式」(Combine Function),以指定每組項目的結合方式。 因此,combinable 類別不限於一組固定的削減運算子。

範例

這個範例使用 OpenMP 和並行執行階段,計算前 35 個 Fibonacci 數字的總和。

// concrt-omp-fibonacci-reduction.cpp 
// compile with: /EHsc /openmp
#include <ppl.h>
#include <iostream>

using namespace concurrency;
using namespace std;

// Computes the nth Fibonacci number. 
// This function illustrates a lengthy operation and is therefore 
// not optimized for performance. 
int fibonacci(int n)
{
   if (n < 2)
      return n;

   // Compute the components in parallel. 
   int n1, n2;
   parallel_invoke(
      [n,&n1] { n1 = fibonacci(n-1); },
      [n,&n2] { n2 = fibonacci(n-2); }
   );

   return n1 + n2;
}

// Uses OpenMP to compute the sum of Fibonacci numbers in parallel. 
void omp_parallel_fibonacci_sum(int count)
{
   int sum = 0;
   #pragma omp parallel for reduction(+ : sum)
      for (int i = 0; i < count; ++i)
      {
         sum += fibonacci(i);
      }

   wcout << L"The sum of the first " << count << L" Fibonacci numbers is " 
         << sum << L'.' << endl;
}

// Uses the Concurrency Runtime to compute the sum of Fibonacci numbers in parallel. 
void concrt_parallel_fibonacci_sum(int count) 
{
   combinable<int> sums;
   parallel_for(0, count, [&sums](int i)
      {
         sums.local() += fibonacci(i);
      });

   wcout << L"The sum of the first " << count << L" Fibonacci numbers is " 
         << sums.combine(plus<int>()) << L'.' << endl;
}

int wmain()
{
   const int count = 35;

   wcout << L"Using OpenMP..." << endl;
   omp_parallel_fibonacci_sum(count);

   wcout << L"Using the Concurrency Runtime..." << endl;
   concrt_parallel_fibonacci_sum(count);
}

這個範例產生下列輸出。

  

如需 combinable 類別的詳細資訊,請參閱 平行容器和物件

編譯程式碼

請複製範例程式碼並將它貼在 Visual Studio 專案中,或是貼在名為 concrt-omp-fibonacci-reduction.cpp 的檔案中,然後在 Visual Studio 的 [命令提示字元] 視窗中執行下列命令。

cl.exe /EHsc /openmp concrt-omp-fibonacci-reduction.cpp

請參閱

概念

從 OpenMP 移轉至並行執行階段

平行容器和物件