mercredi 17 février 2021

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.

Aucun commentaire:

Enregistrer un commentaire