YetiSim Blog

Blogs about simulation and developing YetiSim.

Parallel for_each Algorithm Template

There are a number of for loops in YetiSim which could be replaced by the STL template std::for_each. The loops which are computationally intense could benefit from parallelism using the parallel_for construct, but I wanted a parallel version of for_each. This way I could get into the habit of using the for_each template, and parallelize those constructs easily by changing the namespace from std to tbb.

Here is the code that I wrote, and feedback would be most welcome. It is my hope that it could be bundled directly with TBB as a convenience algorithm template.

/*
* This is a sample implementation of a parallel version of a for_each
* template.
*/

#ifndef __TBB_for_each_H
#define __TBB_for_each_H


#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
#include "tbb/partitioner.h"

namespace tbb {

template<typename InIter, typename Func>
class ApplyToIterator {
public:
ApplyToIterator(Func& f) : _function(f) {
}


void operator()(const blocked_range<InIter>& r) const {
InIter end = r.end();
for(InIter i = r.begin(); i != end; ++i) {
_function(*i);
}
}

private:
Func& _function;

};

template <typename InIter, typename Func>
Func for_each(InIter first, InIter last, Func f) {
parallel_for(blocked_range<InIter>(first, last), ApplyToIterator<InIter, Func>(f), auto_partitioner());
return f;
}


}
#endif


Posted by AJ Guillon  (January 9, 2008)

Leave a Reply