adsense


Friday, 27 November 2015

C++ LANGUAGE PASSING ARGUMENTS TO THREADS

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE PASSING ARGUMENTS TO THREADS




Passing Arguments to Threads 


This example shows how to pass multiple arguments via a structure. 
You can pass any data type in a thread callback because it points 
to void as explained in the following example: 


#include <iostream> 
#include <cstdlib> 
#include <pthread.h> 
 
using namespace std; 
 
#define NUM_THREADS     5 
 
struct thread_data{ 
   int  thread_id; 
   char *message; 
}; 
 
void *PrintHello(void *threadarg) 
{ 
   struct thread_data *my_data; 
 
   my_data = (struct thread_data *) threadarg; 
 
   cout << "Thread ID : " << my_data->thread_id ; 
   cout << " Message : " << my_data->message << endl; 
 
   pthread_exit(NULL); 
} 
 
int main () 
{ 
   pthread_t threads[NUM_THREADS]; 
   struct thread_data td[NUM_THREADS]; 
   int rc; 
   int i; 
 
   for( i=0; i < NUM_THREADS; i++ ){ 
      cout <<"main() : creating thread, " << i << endl; 
      td[i].thread_id = i; 
      td[i].message = "This is message"; 
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&td[i]); 
      if (rc){ 
         cout << "Error:unable to create thread," << rc << endl; 
         exit(-1); 
      } 
   } 
   pthread_exit(NULL); 
} 
When the above code is compiled and executed, it produces the following result: 
main() : creating thread, 0 
main() : creating thread, 1 
main() : creating thread, 2 
main() : creating thread, 3 
main() : creating thread, 4 
Thread ID : 3 Message : This is message 
Thread ID : 2 Message : This is message 
Thread ID : 0 Message : This is message 
Thread ID : 1 Message : This is message 
Thread ID : 4 Message : This is message 


No comments: