I have a single loop which I want to parallelize. The loop implies doing the following:
std::vector<int> input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> output;
for(size_t i(0); i < input.size(); ++i)
{
output.emplace_back(input[i] * 2);
}
However, I would like to preserve the order in the output. I tried to use tbb::enumerable_thread_specific to do that:
tbb::enumerable_thread_specific<std::vector<int>> threadData;
tbb::parallel_for(size_t{0}, input.size(), [&](size_t i)
{
auto& local = threadData.local();
local.emplace_back(2 * input[i]);
});
for (const auto& local : threadData)
{
output.insert(output.begin() + output.size(), local.begin(), local.end());
}
However, the order is not preserved. I also tried to specify the partitioner:
tbb::static_partitioner()
but it didn't help as well.
What is the correct way to parallelize a for loop while preserving the order in the output?