[kaze's test] プログラミングメモ →目次

parallel_for_each()関数

並列パターン ライブラリ (PPL)

parallel_for_each は、指定された関数を範囲内の各要素に並列で適用します。意味的には std 名前空間の for_each 関数と同等ですが、要素に対する反復処理が並列で行われる点、および反復処理の順序が指定されていない点が異なります。引数 _Func は、operator()(T&) の形式の関数呼び出し演算子をサポートしている必要があります (T パラメーターは反復処理するコンテナーの項目の種類を示します)。
 
プロトタイプ:

template <typename _Iterator, typename _Function>
void parallel_for_each(_Iterator _First, _Iterator _Last, const _Function& _Func); 
パラメーターの意味:
__Iterator:
コンテナーを反復処理するために使用する反復子の種類。 

_Function:
範囲内の各要素に適用される関数の種類_Function(Type&)。 

_First:
並列反復処理に含まれる 1 つ目の要素の位置を指定する反復子。 

_Last:
並列反復処理に含まれる最後の要素の 1 つ前の位置を指定する反復子。 

_Func:
範囲内の各要素に適用されるユーザー定義関数オブジェクト。この関数は、ラムダ式、関数ポインター、
またはシグネチャ void operator()(_Index&_type) を持つ関数呼び出し演算子のバージョンを
サポートするオブジェクトになります。


例:配列の個々のエレメントを2倍します。ラムダ式、関数ポインター、またはシグネチャ void operator()(_Index& _type)の三種類の関数のそれぞれの記述方法を示します。

// parallel_for_each_test.cpp
//

#include "stdafx.h"
#include <windows.h>
#include <ppl.h>
#include <iostream>

using namespace Concurrency;
using namespace std;
using namespace std::tr1;

// Function that computes the double of its input.
template
void double_function(Type& n)
{
	n *= 2;
}

// Function object (functor) class that computes the double of its input.
template
class DoubleFunctor
{
public:
	void operator()(Type& n) const
	{
		n *= 2;
	}
};

void print_result(array& values)
{
	// Print each element of the array to the console.
	for_each(values.begin(), values.end(), [](int& n) 
	{ 
		cout << n << endl;
	});
	cout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{

	// Create an array object that contains 5 values.
	array values = { 1, 2, 3, 4, 5 };

	// Use a lambda function, a function object, and a function pointer to 
	// compute the double of each element of the array in parallel.
	parallel_for_each(values.begin(), values.end(), [](int& n){n *= 2;});
	print_result(values);

	// Use a function pointer to double each element.
	parallel_for_each(values.begin(), values.end(), &double_function);
	print_result(values);

	// Use a function object (functor) to double each element.
	parallel_for_each(values.begin(), values.end(), DoubleFunctor());
	print_result(values);

	getchar();
}
出力:
 2
 4
 6
 8
 10
 
 4
 6
 12
 16
 20
 
 8
 12
 24
 32
 40