Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
Announcements
Welcome to the Intel Community. If you get an answer you like, please mark it as an Accepted Solution to help others. Thank you!

parallel_for return vector

digiplant
Beginner
143 Views
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.
[cpp]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 = 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;
}[/cpp]
Problems immediately apparent are 1) original return vector is not modified, a copy is and 2) operator() is const so it cant modify _ReturnVector. Any suggestions as to how to get this to work?
Thanks.
0 Kudos
1 Reply
RafSchietekat
Black Belt
143 Views
ApplyMyComputationFunction's member variables should be references instead, e.g., "vector & _ReturnVector;".
Reply