TBBのインストール

基本ここを真似する。make installができないので精神衛生上よくないように思う。

ヘッダーファイルは/usr/local/include、ライブラリは/usr/local/lib/tbbみたいな感じでおいておいた。

.zshrcには以下を追記。

export TBB21_INSTALL_DIR=/usr/local/lib/tbb
source $TBB21_INSTALL_DIR/build/macos_em64t_gcc_cc4.0.1_os10.5.8_release/tbbvars.sh

stlは基本的に並列化に適していないらしく、TBBでは独自のコンテナを提供している。

vectorに次々につっこんでいくサンプル。

#include <iostream>
#include <algorithm>
#include <vector>

#include <tbb/task_scheduler_init.h>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/concurrent_vector.h>

using namespace std;
using namespace tbb;

concurrent_vector<int> v;
const int NUM = 10;

class PrimePush {
public:
  void operator()(const blocked_range<int>& range) const {
	for(int n = range.begin(); n != range.end();++n) {
	  v.push_back(n);
	}
  };
};

int main() {
  task_scheduler_init TbbInit;
	parallel_for(blocked_range<int>(0, NUM, 3), PrimePush());
	TbbInit.terminate();
	std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout,"\n"));
	return 0;
}

実行結果。入り乱れる。

/tmp% g++ -m64 -I/usr/local/include -ltbb /tmp/aaa.cpp
/tmp% ./a.out 
0
5
1
6
2
7
3
8
9
4