2008-10-28
■[VC++] Parallel Pattern Library
VC++10(VS2010)では、 Parallel Pattern Library (PPL) というのが提供されます。
これは並列処理を行うためのライブラリです。
インクルードするのは <ppl.h> で、名前空間は Concurrency です。
まず、 std::for_each の並列処理版である parallel_for_each
template <typename InputIterator, typename Function> Function parallel_for_each(InputIterator first, InputIterator last, Function func); // ※本当は _Input_iterator _First, ... のようになってますが、読みやすいように勝手に直してます。
#include <iostream> #include <vector> #include <ppl.h> using namespace std; using namespace Concurrency; int main() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } parallel_for_each(v.begin(), v.end(), [](int i) { cout << i << endl; }); }
5 6 7 8 9 0 1 2 3 4
順番を気にせず、高速に全要素を処理を行いたい場合は役立つでしょう。
次に、 for文に相当する並列処理関数 parallel_for
template <typename IndexType, typename Function> Function parallel_for(IndexType first, IndexType last, IndexType step, Function func);
#include <iostream> #include <vector> #include <ppl.h> using namespace std; using namespace Concurrency; int main() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } parallel_for(0, 10, 1, [](int i) { cout << i << endl; }); // for (int i = 0; i < 10; i += 1) と同じ }
8 9 5 6 7 3 4 0 1 2
あとは、複数の関数を並列的に実行する parallel_invoke
template <typename... Functions> void parallel_invoke(Functions&... funcs); // ※VC++10 CTP時点では可変引数テンプレートではなく Function1 〜 Function10 のオーバーロードを作成しています
#include <iostream> #include <array> #include <functional> #include <ppl.h> using namespace std; using namespace std::tr1; using namespace Concurrency; int main() { array<function<void()>, 5> f = { []{ cout << 1 << endl; }, []{ cout << 2 << endl; }, []{ cout << 3 << endl; }, []{ cout << 4 << endl; }, []{ cout << 5 << endl; } }; parallel_invoke(f[0], f[1], f[2], f[3], f[4]); }
5 4 3 2 1
他にもいろいろあるみたいなので、わかったらまた書きます
トラックバック - http://d.hatena.ne.jp/faith_and_brave/20081028/1225184552
リンク元
- 15 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja:official&lr=lang_ja&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=std::min&spell=1
- 14 http://d.hatena.ne.jp/
- 13 http://cpp.ring.hatena.ne.jp/
- 10 http://twitter.com/cpp_akira
- 10 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4SUNA_jaJP292JP293&q=CString+std::string+LPCTSTR
- 6 http://www.google.co.jp/reader/view/
- 6 http://www.google.com/reader/view/
- 5 http://a.hatena.ne.jp/uskz/?gid=290138
- 5 http://reader.livedoor.com/reader/
- 5 http://www.google.co.jp/search?hl=ja&lr=lang_ja&client=firefox-a&rls=org.mozilla:ja:official&hs=Ot3&q=C+++lexical_cast&revid=888337749&sa=X&oi=revisions_inline&resnum=0&ct=top-revision&cd=2