2

Joined execution

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <pthread.h>
  5.  
  6. #include <errno.h>
  7. #include <string.h>
  8.  
  9. #define NTHREADS    3
  10. #define NLOOPS      10
  11.  
  12. void *work( void *p ) {
  13.     int tnum = *(int *) p;
  14.  
  15.     int i;
  16.  
  17.     for ( i = 0; i < NLOOPS; i++ )
  18.         printf( "#%d\n", tnum );
  19.  
  20.     pthread_exit( 0 );
  21. }
  22.  
  23. int main( int argc, char *argv[] ) {
  24.     pthread_t thread[NTHREADS];
  25.     pthread_attr_t attr;
  26.  
  27.     int rc, tnum;
  28.     void *status;
  29.  
  30.     pthread_attr_init( &attr );
  31.     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  32.  
  33.     for ( tnum = 0; tnum < NTHREADS; tnum++ ) {
  34.         rc = pthread_create( &thread[tnum], &attr, work, (void *) &tnum );
  35.         if ( rc )
  36.             fprintf( stderr, "%s\n", strerror( errno ) );
  37.     }
  38.  
  39.     pthread_attr_destroy( &attr );
  40.  
  41.     for ( tnum = 0; tnum < NTHREADS; tnum++ ) {
  42.         rc = pthread_join( thread[tnum], &status );
  43.         if ( rc )
  44.             fprintf( stderr, "%s\n", strerror( errno ) );
  45.         printf( "Completed join with thread #%d status=%ld\n", tnum, (long) status );
  46.     }
  47.  
  48.     pthread_exit( 0 );
  49. }
$ gcc -Wall -lpthread join.c -o join
$ ./join
#1
...
#0
...
Completed join with thread #0 status=0
...
#2
Completed join with thread #1 status=0
Completed join with thread #2 status=0

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].