共用方式為


如何:撰寫 parallel_for_each 迴圈

這個範例將示範如何使用 concurrency::parallel_for_each 演算法,以平行方式計算 std::array 物件中質數的計數。

範例

下列範例會計算陣列中質數的計數兩次。 此範例會先使用 std::for_each 演算法來循序計算計數。 然後,此範例會使用 parallel_for_each 演算法,以平行方式執行相同的工作。 範例也會將執行這兩個計算的所需時間列印至主控台。

// parallel-count-primes.cpp 
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <iostream>
#include <algorithm>
#include <array>

using namespace concurrency;
using namespace std;

// Calls the provided work function and returns the number of milliseconds  
// that it takes to call that function. 
template <class Function>
__int64 time_call(Function&& f)
{
   __int64 begin = GetTickCount();
   f();
   return GetTickCount() - begin;
}

// Determines whether the input value is prime. 
bool is_prime(int n)
{
   if (n < 2)
      return false;
   for (int i = 2; i < n; ++i)
   {
      if ((n % i) == 0)
         return false;
   }
   return true;
}

int wmain()
{
   // Create an array object that contains 200000 integers. 
   array<int, 200000> a;

   // Initialize the array such that a[i] == i. 
   int n = 0;
   generate(begin(a), end(a), [&] {
      return n++;
   });

   LONG prime_count;
   __int64 elapsed;

   // Use the for_each algorithm to count the number of prime numbers 
   // in the array serially.
   prime_count = 0L;
   elapsed = time_call([&] {
      for_each (begin(a), end(a), [&](int n ) { 
         if (is_prime(n))
            ++prime_count;
      });
   });
   wcout << L"serial version: " << endl
         << L"found " << prime_count << L" prime numbers" << endl
         << L"took " << elapsed << L" ms" << endl << endl;

   // Use the parallel_for_each algorithm to count the number of prime numbers 
   // in the array in parallel.
   prime_count = 0L;
   elapsed = time_call([&] {
      parallel_for_each (begin(a), end(a), [&](int n ) { 
         if (is_prime(n))
            InterlockedIncrement(&prime_count);
      });
   });
   wcout << L"parallel version: " << endl
         << L"found " << prime_count << L" prime numbers" << endl
         << L"took " << elapsed << L" ms" << endl << endl;
}

下列是針對配備四個處理器之電腦的範例輸出。

  

編譯程式碼

若要編譯程式碼,請複製該程式碼,然後將它貼入 Visual Studio 專案中,或貼入名為 parallel-count-primes.cpp 的檔案,然後在 Visual Studio 的 [命令提示字元] 視窗中執行下列命令。

cl.exe /EHsc parallel-count-primes.cpp

穩固程式設計

此範例傳遞給 parallel_for_each 演算法的 Lambda 運算式會使用 InterlockedIncrement 函式來啟用迴圈的平行反覆項目,以便同時遞增計數器。 如果您使用 InterlockedIncrement 等函式來同步處理共用資源的存取權,可能會在您的程式碼中呈現效能瓶頸。 您可以使用無鎖定同步處理機制 (例如 concurrency::combinable 類別) 來排除共用資源的同時存取。 如需以這種方式使用 combinable 類別的範例,請參閱 如何:使用可組合的類別改善效能

請參閱

參考

parallel_for_each 函式

概念

平行演算法