mercredi 11 décembre 2019

What is the proper of constructing multiple threads when specific attention is given to performance?

I want to know when using a lambda expression to define the thread, will it help to improve some performance gain. In my case, I have to run several threads. This is for real-time based application. Hence, if someone suggests to me what would be the optimal way of creating several threads. Creating threads happens in each iteration. Thus, this is a kind of expensive operation which is to be optimized.

  #include <iostream>
  #include <thread>
  #include <vector>
  #include <algorithm>

  class Task
  {
  public:
    void execute(std::string command)
    {
      //TODO actual logic
      for(int i = 0; i < 5; i++)
      {
        std::cout<<command<<std::endl;
      }
    }
  };

  int main()
  {

      Task* taskPtr = new Task();
      std::vector<std::thread> workers_older;
      for (int i = 0; i < 2; i++) {
          workers_older.push_back(std::thread(&Task::execute, taskPtr, "Task: without lambda expression"+ std::to_string(i)));
      }
      std::for_each(workers_older.begin(), workers_older.end(), [](std::thread &t) 
      {
          t.join();
      });

      std::vector<std::thread> workers;
      for (int i = 0; i < 2; i++) {
          workers.push_back(std::thread([&]() 
          {
              taskPtr->execute("Task: "+ std::to_string(i));
          }));
      }
      std::for_each(workers.begin(), workers.end(), [](std::thread &t) 
      {
          t.join();
      });
      return 0;
  }

Aucun commentaire:

Enregistrer un commentaire