c++并行计算库TBB和PPL的基本用法(二)
egin,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, 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 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, 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 result)
{
cout << "First task to finish returns "
<< result.first
<< " and has index "
<< result.second<
}).wait();
//output: First task to finish returns 42 and has index 1.
复制代码
总结:
ppl和tbb两个并行运算库功能相似,如果需要跨平台则选择tbb, 否则选择ppl。ppl在任务调度上比tbb强大,tbb由于设计上的原因不能做到任务的连续执行以及任务的组合,但是tbb有跨平台的优势。