如何:使用 combinable 组合多个集
本主题演示如何使用 Concurrency::combinable 类计算质数集。
示例
下面的示例将质数集计算两次。 每次计算都会将结果存储在 std::bitset 对象中。 此示例首先按顺序计算该集,然后以并行方式计算该集。 此示例还会将执行两次计算所需的时间输出到控制台。
此示例使用 Concurrency::parallel_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 2010 命令提示符窗口中运行以下命令。
cl.exe /EHsc parallel-combine-primes.cpp