I'm having a for loop which I would like to convert into parallel_for fnc invocation. My code meets all the criteria (described in Parallel_Programming_with_Microsoft_Visual_C_plus_plus,p.7) for this conversion to be successfull, yet I find it difficult to implement. Here is my example:
//"Oridinary" for
//numbers_from_file_ is a vector<Big_Int> loaded with Big_Int
//results_ is a vector<Big_Int>
for (unsigned i = 0; i < numbers_from_file_.size(); i += 2)//+2 to skip to another pair
{
results_.push_back( numbers_from_file_[i] * numbers_from_file_[i + 1]);
}
The scenario is that each pair of numbers f开发者_JAVA技巧rom numbers_from_file_ is multiplied out and stored in results_. In order to make it work the variable i has to be incremented by two (to skip to another pair). Unfortunately example in this book is showing how to convert body of for loop into parallel_for fnc invocation only if i is being incremented by one.
Is it possible to convert my loop into parallel_for fnc invocation?MSDN says that there is a step
parameter. Use it.
Yes, you can. You will need to resize results first and then add to it.
results_.resize(numbers_from_file.size() / 2);
parallel_for(static_cast<std::size_t>(0), numbers_from_file_.size(), static_cast<std::size_t>(2), [&](std::size_t i) {
results_[i / 2] = numbers_from_file_[i] * numbers_from_file_[i + 1]);
});
This is just quick, of course, no guarantees, but it should be pretty directly replacable.
Your code appears to be identical to
for (unsigned j = 0; j < numbers_from_file_.size()/2; ++j)
{
results_.push_back( numbers_from_file_[2*j] * numbers_from_file_[2*j + 1]);
}
精彩评论