0

I have an array containing vectors

std::vector<int> A[10];

I want to copy all the values from all the vectors from array A to another vector of integers B using multithreading

std::vector<int> B;

In order to do that in multithreading, I have an array containing positions where each vector from array A will be in the vector B. And to copy, I am using lambda expression:

int positions[10];

for (int i = 0; i < 10; i++)
{
   std::async( std::launch::async, [](std::vector<uint32_t>::iterator first, std::vector<uint32_t>::iterator last, std::vector<uint32_t>::iterator d_first)  {std::copy(first, last, d_first);}, (*A[i]).begin(), (*A[i]).end(), B.begin() + positions[i]));
}

Now this is working fine. It creates 10 threads and each thread copies vector from array A to B with defined positions. But the problem is, it needs copy all the values using limited threads. For example 2.

Then instead of passing one vector for copy in lambda function I need to pass 5 vectors(then of course position array will have only two position values) for each thread.

Is there any way I can modify the lambda function to do that? Or any other possible solution?

Thank you in advance :)

Nik
  • 113
  • 1
  • 5
  • Why not `wait` or `get` on a `future` if you've started max number of async tasks? Also, be sure to check the performance. Appending 10 vectors to one vectors in a serial manner is often very quick. Also, are you sure your code doesn't have UB? It seems to me like you are appending to `B` from multiple threads at the same time. That's usually a recipe for disaster (UB). – Ted Lyngmo Feb 11 '21 at 23:08
  • 1
    Instead of reinventing the wheel, why not use some parallel algorithm or parallel loop? You might read https://devblogs.microsoft.com/cppblog/using-c17-parallel-algorithms-for-better-performance/. – Phil1970 Feb 11 '21 at 23:27
  • I agree with Phil, maybe just use std::copy<> and pass it a parallel execution policy? https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t – N. Prone Feb 11 '21 at 23:45

0 Answers0