在多核的平臺上開發(fā)并行化的程序,必須合理地利用系統(tǒng)的資源 - 如與內(nèi)核數(shù)目相匹配的線程,內(nèi)存的合理訪問次序,最大化重用緩存。有時候用戶使用(系統(tǒng))低級的應(yīng)用接口創(chuàng)建、管理線程,很難保證是否程序處于最佳狀態(tài)。
Intel Thread Building Blocks (TBB) 很好地解決了上述問題:
- TBB提供C++模版庫,用戶不必關(guān)注線程,而專注任務(wù)本身。
- 抽象層僅需很少的接口代碼,性能上毫不遜色。
- 靈活地適合不同的多核平臺。
- 線程庫的接口適合于跨平臺的移植(Linux, Windows, Mac)
- 支持的C++編譯器 – Microsoft, GNU and Intel
主要的功能:
1)通用的并行算法
循環(huán)的并行:
parallel_for, parallel_reduce – 相對獨(dú)立的循環(huán)層
parallel_scan – 依賴于上一層的結(jié)果
流的并行算法
parallel_while – 用于非結(jié)構(gòu)化的流或堆
pipeline - 對流水線的每一階段并行,有效使用緩存
并行排序
parallel_sort – 并行快速排序,調(diào)用了parallel_for
2)任務(wù)調(diào)度者
管理線程池,及隱藏本地線程復(fù)雜度
并行算法的實(shí)現(xiàn)由任務(wù)調(diào)度者的接口完成
任務(wù)調(diào)度者的設(shè)計(jì)考慮到本地線程的并行所引起的性能問題
3)并行容器
concurrent_hash_map
concurrent_vector
concurrent_queue
4)同步原語
atomic
mutex
spin_mutex – 適合于較小的敏感區(qū)域
queuing_mutex – 線程按次序等待(獲得)一個鎖
spin_rw_mutex
queuing_rw_mutex
說明:使用read-writer mutex允許對多線程開放”讀”操作
5)高性能的內(nèi)存申請
使用TBB的allocator 代替 C語言的 malloc/realloc/free 調(diào)用
使用TBB的allocator 代替 C++語言的 new/delete 操作
使用TBB的例子 – task
- #include “tbb/task_scheduler_init.h”
- #include “tbb/task.h”
- using namespace tbb;
- class ThisIsATask: public task {
- public:
- task* execute () {
- WORK ();
- return NULL;
- }
- };
-
- class MyRootTask: public task {
- public:
- task* execute () {
- for (int i=0; i <N; i++) {
- task& my_task =
- *new (task::allocate_additional_child_of (*this))
- ThisIsATask ();
- spawn (my_task);
- }
- wait_for_all ();
- return NULL;
- }
- };
-
- int main () {
- task_scheduler_init my_tbb;
- task& my_root =
- *new (task::allocate_root()) MyRootTask ();
- my_root.set_ref_count (1);
- task::spawn_root_and_wait (my_root);
- return 0;
- }
posted on 2011-01-14 13:55
老馬驛站 閱讀(1513)
評論(0) 編輯 收藏 引用 所屬分類:
tbb