如何:使用可組合的類別結合集合
本主題說明如何使用 concurrency::combinable 類別來計算質數集合。
範例
下列範例會計算質數集合兩次。 每個計算都會將結果儲存在 std::bitset 物件中。 此範例會先以序列方式計算集合,然後以平行方式計算集合。 這個範例也會將執行這兩項計算所需的時間列印到主控台。
此範例會使用 concurrency::p arallel_for 演算法和 combinable
對象來產生線程區域集。 然後,它會使用 concurrency::combinable::combine_each 方法,將線程區域集合合併至最終集合。
// parallel-combine-primes.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <bitset>
#include <iostream>
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;
}
const int limit = 40000;
int wmain()
{
// A set of prime numbers that is computed serially.
bitset<limit> primes1;
// A set of prime numbers that is computed in parallel.
bitset<limit> primes2;
__int64 elapsed;
// Compute the set of prime numbers in a serial loop.
elapsed = time_call([&]
{
for(int i = 0; i < limit; ++i) {
if (is_prime(i))
primes1.set(i);
}
});
wcout << L"serial time: " << elapsed << L" ms" << endl << endl;
// Compute the same set of numbers in parallel.
elapsed = time_call([&]
{
// Use a parallel_for loop and a combinable object to compute
// the set in parallel.
// You do not need to synchronize access to the set because the
// combinable object provides a separate bitset object to each thread.
combinable<bitset<limit>> working;
parallel_for(0, limit, [&](int i) {
if (is_prime(i))
working.local().set(i);
});
// Merge each thread-local computation into the final result.
working.combine_each([&](bitset<limit>& local) {
primes2 |= local;
});
});
wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;
}
下列範例輸出適用於具有四個處理器的電腦。
serial time: 312 ms
parallel time: 78 ms
編譯程式碼
複製範例程式代碼,並將其貼到 Visual Studio 專案中,或貼到名為 parallel-combine-primes.cpp
的檔案中,然後在 Visual Studio 命令提示字元視窗中執行下列命令。
cl.exe /EHsc parallel-combine-primes.cpp