yohhoyの日記

技術的メモをしていきたい日記

STLアルゴリズムのParallel Mode拡張

id:ignisanさんのC++ Advent Calendar 2011 記事で知った gcc Parallel Mode 拡張についてメモ。

http://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html

Runtime Library (libstdc++)

  • An experimental parallel mode has been added. This is a parallel implementation of many C++ Standard library algorithms, like std::accumulate, std::for_each, std::transform, or std::sort, to give but four examples. These algorithms can be substituted for the normal (sequential) libstdc++ algorithms on a piecemeal basis, or all existing algorithms can be transformed via the -D_GLIBCXX_PARALLEL macro.
http://gcc.gnu.org/gcc-4.3/changes.html

gcc/libstdc++では独自拡張として、標準ヘッダ <algorithm>, <numeric> で提供されるSTLアルゴリズムの並列実装を提供する。MCSTL*1に基づいており、内部実装はOpenMPベース。STLアルゴリズムの“内部実装”として提供されるため、インタフェースはSTLアルゴリズム関数と互換性がある*2

コンパイル時にマクロ_GLIBCXX_PARALLELを有効にするだけで利用可能(OpenMPサポートを有効にする -fopenmp オプション指定も必要)。

g++ input.cpp -D_GLIBCXX_PARALLEL -fopenmp

またコード上で明示的に並列実装を利用することもできる。明示的に利用する場合、標準ヘッダの代わりにヘッダ <parallel/algorithm>, <parallel/numeric> をincludeし、名前空間stdの代わりに名前空間__gnu_parallel以下のSTLアルゴリズムと同名の関数テンプレートを使えばよい。(例:std::sort__gnu_parallel::sort

関連URL

*1:The Multi-Core Standard Template Library

*2:ちなみに Intel TBB や Microsoft PPL では、STLアルゴリズムと似ているものの並列処理向けにAPIが再設計されている。