随笔-167  评论-8  文章-0  trackbacks-0

在多核的平台上开发并行化的程序,必须合理地利用系统的资源 - 如与内核数目相匹配的线程,内存的合理访问次序,最大化重用缓存。有时候用户使用(系统)低级的应用接口创建、管理线程,很难保证是否程序处于最佳状态。 

Intel Thread Building Blocks (TBB) 很好地解决了上述问题: 

  • TBB提供C++模版库,用户不必关注线程,而专注任务本身。
  • 抽象层仅需很少的接口代码,性能上毫不逊色。
  • 灵活地适合不同的多核平台。
  • 线程库的接口适合于跨平台的移植(Linux, Windows, Mac)
  • 支持的C++编译器 – Microsoft, GNU and Intel 

主要的功能:

1)通用的并行算法

循环的并行: 
parallel_for, parallel_reduce – 相对独立的循环层 
parallel_scan – 依赖于上一层的结果 
流的并行算法 
parallel_while – 用于非结构化的流或堆 
pipeline - 对流水线的每一阶段并行,有效使用缓存 
并行排序 
parallel_sort – 并行快速排序,调用了parallel_for 

2)任务调度者

管理线程池,及隐藏本地线程复杂度 
并行算法的实现由任务调度者的接口完成 
任务调度者的设计考虑到本地线程的并行所引起的性能问题 

3)并行容器

concurrent_hash_map 
concurrent_vector 
concurrent_queue 

4)同步原语

atomic 
mutex 
spin_mutex – 适合于较小的敏感区域 
queuing_mutex – 线程按次序等待(获得)一个锁 
spin_rw_mutex 
queuing_rw_mutex 
说明:使用read-writer mutex允许对多线程开放”读”操作 

5)高性能的内存申请

使用TBB的allocator 代替 C语言的 malloc/realloc/free 调用 
使用TBB的allocator 代替 C++语言的 new/delete 操作 

使用TBB的例子 – task

  1. #include “tbb/task_scheduler_init.h”
  2. #include “tbb/task.h”
  3. using namespace tbb;
  4. class ThisIsATask: public task {
  5. public:
  6.     task* execute () {
  7.         WORK ();
  8.         return NULL;
  9.     }
  10. };
  11.  
  12. class MyRootTask: public task {
  13. public:
  14.     task* execute () {
  15.         for (int i=0; i <N; i++) {
  16.             task& my_task = 
  17.                 *new (task::allocate_additional_child_of (*this)) 
  18.                     ThisIsATask ();
  19.             spawn (my_task);
  20.         }
  21.         wait_for_all ();
  22.         return NULL;
  23.     }
  24. };
  25.  
  26. int main () {
  27.     task_scheduler_init my_tbb;  // 创建线程池
  28.     task& my_root =
  29.         *new (task::allocate_root()) MyRootTask ();
  30.     my_root.set_ref_count (1);
  31.     task::spawn_root_and_wait (my_root); // 开始Root Task任务
  32.     return 0;
  33. }
posted on 2011-01-14 13:55 老马驿站 阅读(1477) 评论(0)  编辑 收藏 引用 所属分类: tbb