TBB任务
task_group表示可以等待或者取消的任务集合
task_group g;
g.run([]{TestPrint(); });
g.run([]{TestPrint(); });
g.run([]{TestPrint(); });
g.wait();
PPL(Parallel Patterns Library)
PPL是微软开发的并行计算库,它的功能和TBB是差不多的,但是PPL只能在windows上使用。二者在并行算法的使用上基本上是一样的, 但还是有差异的。二者的差异:
parallel_reduce的原型有些不同,PPL的paraller_reduce函数多一个参数,原型为parallel_reduce(begin,end,identity,func,reduction), 比tbb多了一个参数,但是表达的意思差不多,一个是区间,一个是区间迭代器。
PPL中没有parallel_pipeline接口。
TBB的task没有PPL的task强大,PPL的task可以链式连续执行还可以组合任务,TBB的task则不行。
PPL任务的链式连续执行then
复制代码
int main()
{
auto t = create_task([]() -> int
{
return 0;
});
// Create a lambda that increments its input value.
auto increment = [](int n) { return n + 1; };
// Run a chain of continuations and print the result.
int result = t.then(increment)。then(increment)。then(increment)。get();
cout 《 result 《 endl;
}
/* Output:
3
*/
复制代码
PPL任务的组合
1.when_all可以执行一组任务,所有任务完成之后将所有任务的结果返回到一个集合中。要求该组任务中的所有任务的返回值类型都相同。
复制代码
array<task<int>, 3> tasks =
{
create_task([]() -> int { return 88; }),
create_task([]() -> int { return 42; }),
create_task([]() -> int { return 99; })
};
auto joinTask = when_all(begin(tasks), end(tasks))。then([](vector<int> results)
{
cout 《 "The sum is "
《 accumulate(begin(results), end(results), 0)
《 '.' 《 endl;
});
// Print a message from the joining thread.
cout 《 "Hello from the joining thread." 《 endl;
// Wait for the tasks to finish.
joinTask.wait();
复制代码
2.when_any任务组中的某一个任务执行完成之后,返回一个pair,键值对是结果和任务序号。
复制代码
array<task<int>, 3> tasks = {
create_task([]() -> int { return 88; }),
create_task([]() -> int { return 42; }),
create_task([]() -> int { return 99; })
};
// Select the first to finish.
when_any(begin(tasks), end(tasks))。then([](pair<int, size_t> result)
{
cout 《 "First task to finish returns "
《 result.first
《 " and has index "
《 result.second《endl;
})。wait();
//output: First task to finish returns 42 and has index 1.
复制代码
总结:
ppl和tbb两个并行运算库功能相似,如果需要跨平台则选择tbb, 否则选择ppl.ppl在任务调度上比tbb强大,tbb由于设计上的原因不能做到任务的连续执行以及任务的组合,但是tbb有跨平台的优势。