adsense


Friday, 27 November 2015

C++ LANGUAGE TERMINATING THREADS

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



C++ LANGUAGE TERMINATING THREADS





Terminating Threads 


There is following routine which we use to terminate a POSIX thread: 

#include <pthread.h> 

pthread_exit (status)  

Here pthread_exit is used to explicitly exit a thread. 
Typically, the pthread_exit() routine is called after a 
thread has completed its work and is no longer required to exist. 

If main() finishes before the threads it has created, and exits 
with pthread_exit(), the other threads will continue to execute. 
Otherwise, they will be automatically terminated when main() finishes. 

Example: 

This simple example code creates 5 threads with the pthread_create() 
routine. Each thread prints a "Hello World!" message, and then terminates 
with a call to pthread_exit().
 
#include <iostream> 

#include <cstdlib> 
#include <pthread.h> 
 
using namespace std; 
 
#define NUM_THREADS     5 
 
void *PrintHello(void *threadid) 
{ 
   long tid; 
   tid = (long)threadid; 
   cout << "Hello World! Thread ID, " << tid << endl; 
   pthread_exit(NULL); 
} 
 
int main () 
{ 
   pthread_t threads[NUM_THREADS]; 
   int rc; 
   int i; 
   for( i=0; i < NUM_THREADS; i++ ){ 
      cout << "main() : creating thread, " << i << endl; 
      rc = pthread_create(&threads[i], NULL,  
                          PrintHello, (void *)i); 
      if (rc){ 
         cout << "Error:unable to create thread," << rc << endl; 
         exit(-1); 
      } 
   } 
   pthread_exit(NULL); 
} 
Compile the following program using -lpthread library as follows: 
$gcc test.cpp -lpthread 
Now, execute your program which gives the following output: 
main() : creating thread, 0 
main() : creating thread, 1 
main() : creating thread, 2 
main() : creating thread, 3 
main() : creating thread, 4 
Hello World! Thread ID, 0 
Hello World! Thread ID, 1 
Hello World! Thread ID, 2 
Hello World! Thread ID, 3 
Hello World! Thread ID, 4 


No comments: