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

#define N 20

using namespace std;
using namespace tbb;

void func( long *x)
{
	(*x) = -2;
}

/*
 * FObject uses its overloaded operator "()" to create a pool of threads of
 * appropriate grainsize and specifies the task for each thread. Each thread
 * has its own local memory to work with.
 */
class FObject {
	private:
		long *x;

	public:
		FObject( long _a[] )
		{
			x = _a;
		}

		void operator( )( const blocked_range<long> &r ) const {
			printf("%09ld - %09ld\n", (long) r.begin(), (long) r.end());

			for ( long i=r.begin(); i!=r.end( ); ++i ) {
				func( &x[i] );
			}
		}
};

/*
 * par_func is a wrapper function that uses parallel_for to parallize the task
 */
void par_func(long x, long y, long *a)
{
	FObject ob(a);

	parallel_for(blocked_range<long>(x+2,y-3,2), FObject(ob));
}

int main()
{
	task_scheduler_init init(-1);

	long a[N];

	for ( long i=0; i<N; i++ ) {
		a[i] = i;
	}

	par_func(0,N,a);	// reset parallelly all values to -2.0

	cout << endl;
	for ( long i=0; i<5; i++ ) {
		printf("a[%09ld] = %ld\n",i,a[i]);
	}
	cout << endl;
	for ( long i=N-5; i<N; i++ ) {
		printf("a[%09ld] = %ld\n",i,a[i]);
	}

	return 0;
}

