morsingher
morsingher

Reputation: 31

C++ process each element of a vector in parallel with threads

I am kinda new to modern C++ multi-threading and I would like to know which would be the correct approach to process each element of a vector in parallel. To be more concrete, assume the following situation:

struct Neighbor
{
  int idx;
  float score;
};

struct Cluster
{
  std::vector<int> cameras;
  std::unordered_map<int, std::vector<Neighbor>> neighbors;
};

class Test
{
  std::vector<Cluster> clusters;
  void DoSomething();
  void DoSomethingForCluster(const int i);
};

I would like to process each element of the clusters vector (i.e. fill the map inside) in parallel, since there is no dependency between each element. My first guess is to try something like:

void Test::DoSomething()
{
  std::vector<std::thread> th_vec;

  for (int i = 0; i < clusters.size(); i++)
  {
    th_vec.push_back(std::thread(&Test::DoSomethingForCluster, this, i));
  }

  for (auto& t : th_vec)
  {
    t.join();
  }
}

void Test::DoSomethingForCluster(const int i)
{
  for (const auto& cam : clusters[i].cameras)
  {
    std::vector<Neighbor> n;
    // Do something to fill the vector n
    clusters[i].neighbors.insert(std::make_pair(cam, n));
  }
}

The code builds and runs smoothly, but I would like to understand if there is a better or more efficient way to do this sort of task. For example, does it make sense to launch a thread for each element? Any advice or help is highly appreciated, thank you in advance.

Upvotes: 0

Views: 1091

Answers (1)

Joseph Larson
Joseph Larson

Reputation: 9058

I haven't done this myself, but I think the way you would do this is with for_each and an execution policy:

std::for_each(std::execution::parallel_policy, clusters.begin(), clusters.end() []() {....} );

Let the library decide how many threads to create.

You can google about "C++ execution policy" to get a little more info.

Upvotes: 1

Related Questions