共用方式為


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

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

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

平行模式文件庫 (PPL) 提供 concurrency::combinable 類別,提供可重複使用、 執行緒區域儲存區,可讓您執行更細緻的運算,然後將這些計算合併到最終的結果。 combinable 類別是作用於純量和複雜型別的範本。 若要使用combinable類別、 執行的平行建構函式主體中的 sub-computations,然後呼叫 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);
}

這個範例產生下列輸出。

Using OpenMP...
The sum of the first 35 Fibonacci numbers is 14930351.
Using the Concurrency Runtime...
The sum of the first 35 Fibonacci numbers is 14930351.

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

編譯程式碼

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

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

請參閱

概念

從 OpenMP 移轉至並行執行階段

平行容器和物件