parallel_for return vector

parallel_for return vector

Hi, I'm brand new to TBB, and trying to solve my first problem.

What I want is a function "MyParallelFunction" that takes as an input a vector of "MyCustomClass1" objects and returns a vector of "MyCustomClass2" objects. The return vector of MyCustomClass2 objects should be populated by the parallel invocation of the function "MyComputationFunction" taking a single MyCustomClass1 object and returning a single MyCustomClass2 object.I mentioned I'm a beginner with TBB; I'm farily confused about how to achieve this result. Most of the examples I see use arrays, instead of vectors. I've tried several things, included below is one. Note that I know this is wrong, but I'm including it so you know that I've tried something and possibly clarify what I'm attempting to accomplish.

class ApplyMyComputationFunction
{
     vector _ReturnVector;
     vector _InputVector;

public:
     void operator()(const blocked_range& range) const
     {
         for (size_t i = range.begin(); i != range.end(); ++i)
         {
              _ReturnVector[i] = MyComputationFunction(_InputVector);
         }
     }
     
     ApplyMyComputationFunction(vector& returnVector, vector& inputVector)
     {
         _ReturnVector = returnVector;
         _InputVector = inputVector;
     }
};


vector MyParallelFunction(vector inputObjects)
{
     // initialize vector size
     size_t vectorSize = inputObjects.size();

     // initialize return vector to size vectorSize
     vector returnVector(vectorSize, MyCustomClass2());

    // fill return vector with values in parallel
    parallel_for(blocked_range(0, vectorSize), ApplyMyComputationFunction(returnVector, inputObjects);

    // return result vector
    return returnVector;
}

Problems immediately apparent are 1) original return vector is not modified, a copy is and 2) operator() is const so it cant modify _ReturnVector[i]. Any suggestions as to how to get this to work?Thanks.

2 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

ApplyMyComputationFunction's member variables should be references instead, e.g., "vector & _ReturnVector;".

Leave a Comment

Please sign in to add a comment. Not a member? Join today