mercredi 30 mars 2016

how to put dynamic size of array of threads

As you can see, I want to create few threads.Now number of threads depends on the command line argument I get from console, so basically no of threads to be created has to be dynamic but creating array of objects of thread class in C++11 requires a const size to be given and that is where my problem arises as it is only accepting "num_threads" when it is initialized without using a variable(i.,e using a literal ).
Like: static const int num_threads=10;
But not in case of: static const int num_threads=stoi(argv[1]);

int main(int argc, char *argv[])
{
  if(argc!=2)
  {
     cout << "\n Invalid arguments \n";
     return 0;
  }

  static  const int num_threads = 10;// stoi(argv[1]);//
  thread t[num_threads];


 //Launch a group of threads
 for (int i = 0; i < num_threads; ++i) 
 {
    t[i] = std::thread(call_from_main_to_connect_info_disconnect, i);
 }

 std::cout << "Launched from the main\n";

//Join the threads with the main thread
 for (int i = 0; i < num_threads; ++i) 
 {
    t[i].join();
 }

 getchar();
 return err;

}

Any suggestions in order to have no of threads dynamic through command line input?

Aucun commentaire:

Enregistrer un commentaire