create Pthreads in loop

11.9k Views Asked by At

I create some threads in a for loop and after this loop, join them in other loop. they do their function till all of them finish it,do they? my last result is logically wrong . my result is correct, just when join each thread after create it!!

1

There are 1 best solutions below

3
On

Yes i think you are doing right.Letsee for example

extern "C"
 {
    #include <pthread.h>
    #include <unistd.h>
 }
#include <iostream>

using namespace std;

const int NUMBER_OF_THREADS = 5;

void * thread_talk(void * thread_nr)

{
     //do some operation here
     pthread_exit(NULL);         //exit from current thread
}

int main()

{

  pthread_t thread[NUMBER_OF_THREADS];

  cout << "Starting all threads..." << endl;

  int temp_arg[NUMBER_OF_THREADS] ;

  /*creating all threads*/
  for(int current_t = 0; current_t < NUMBER_OF_THREADS; current_t++)
  {

   temp_arg[current_t]   = current_t;

   int result = pthread_create(&thread[current_t], NULL, thread_talk, static_cast<void*>(&temp_arg[current_t]))  ;

   if (result !=0)
   {
   cout << "Error creating thread " << current_t << ". Return code:" << result <<  endl;
   }

  }

 /*creating all threads*/

/*Joining all threads*/
for(int current_t = 0; current_t < NUMBER_OF_THREADS; current_t++)
{
 pthread_join(thread[current_t], NULL);
}

/*Joining all threads*/
cout << "All threads completed." ;

return 0;
}

Its your decision when you want to exit that thread by calling pthread_exit function .Absolutely there is no certainty that which thread will be executed first.Your OS will decide when resources are available for your threads and execute them on whatever CPU is least occupied