设为首页 加入收藏

TOP

c++并行计算库TBB和PPL的用法(三)
2014-02-08 13:36:15 来源: 作者: 【 】 浏览:266
Tags:并行 计算 TBB PPL 用法

 

  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有跨平台的优势。

      

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++线段树求区间交,并,补 下一篇C++ Primer Plus:处理..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)
·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)