home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / GianuzziV / SO1 / HelloThread.c < prev    next >
C/C++ Source or Header  |  2005-04-03  |  1KB  |  49 lines

  1. /********************************************************
  2. *                                                       *
  3. *  Multi-threaded "Hello World"                         *
  4. *  sono creati 2 thread, uno scrive Hello, l'altro Word *
  5. *                                                       *
  6. * gcc -D_REENTRANT HelloThread.c -lpthread              *
  7. *                                                       *
  8. ********************************************************/
  9.  
  10.  
  11. #include <pthread.h>
  12. #include <stdio.h>
  13.  
  14. void* output( void* );
  15.  
  16. /* mutex variables */
  17. pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER;
  18.  
  19. int main( void )
  20. {
  21.   pthread_t thr1, thr2;
  22.   const char* msg1 = "Hello ";
  23.   const char* msg2 = "world ";
  24.   
  25.   pthread_create( &thr1, NULL, output, (void*)msg1 );
  26.   pthread_create( &thr2, NULL, output, (void*)msg2 );
  27.  
  28.   pthread_join( thr1, NULL );
  29.   pthread_join( thr2, NULL );
  30.  
  31.   printf( "\n" );
  32.  
  33.   return 0;
  34. }
  35.  
  36.  
  37. void* output( void* msg )
  38. {
  39.   int i;
  40.  
  41.   for( i = 0; i < 10; ++i ) {
  42.     pthread_mutex_lock( &Lock );
  43.     printf( (char*)msg );
  44.     pthread_mutex_unlock( &Lock );
  45.   }
  46.   return NULL;
  47. }
  48.  
  49.