C++11の機能によるparallel_for

C++11からは,std::threadというのが追加され,マルチスレッドプログラミングが標準で使えるようになった.
その機能を使って,std::for_each的な処理をマルチスレッド化したいなと思って調べたら以下のページが見つかった.
A parallel for using std::thread? | stackoverflow
やり方について色々議論があるけど,最後に出ている次のようなコードが良さそう.

template<typename Iterator, class Function>
void parallel_for(const Iterator& first, const Iterator& last, Function&& f, const int nthreads = 1, const int threshold = 1000)
{
    const unsigned int group = std::max(std::max(ptrdiff_t(1), ptrdiff_t(std::abs(threshold))), ((last-first))/std::abs(nthreads));
    std::vector<std::thread> threads;
    Iterator it = first;
    for (; it < last-group; it += group) {
        threads.push_back(std::thread([=,&f](){std::for_each(it, std::min(it+group, last), f);}));
    }
    std::for_each(it, last, f); // use calling thread while we wait for the others
    std::for_each(threads.begin(), threads.end(), [](std::thread& x){x.join();});
}

これは次のように利用できる.

std::vector<double> data={1,2,3,4,5};
for_each(data.begin(), data.end(), [](const int& i){
    // i を使った処理
});

という感じで使える.

コメントする