2
Joined execution
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <errno.h>
- #include <string.h>
- #define NTHREADS 3
- #define NLOOPS 10
- void *work( void *p ) {
- int tnum = *(int *) p;
- int i;
- for ( i = 0; i < NLOOPS; i++ )
- printf( "#%d\n", tnum );
- pthread_exit( 0 );
- }
- int main( int argc, char *argv[] ) {
- pthread_t thread[NTHREADS];
- pthread_attr_t attr;
- int rc, tnum;
- void *status;
- pthread_attr_init( &attr );
- pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
- for ( tnum = 0; tnum < NTHREADS; tnum++ ) {
- rc = pthread_create( &thread[tnum], &attr, work, (void *) &tnum );
- if ( rc )
- fprintf( stderr, "%s\n", strerror( errno ) );
- }
- pthread_attr_destroy( &attr );
- for ( tnum = 0; tnum < NTHREADS; tnum++ ) {
- rc = pthread_join( thread[tnum], &status );
- if ( rc )
- fprintf( stderr, "%s\n", strerror( errno ) );
- printf( "Completed join with thread #%d status=%ld\n", tnum, (long) status );
- }
- pthread_exit( 0 );
- }
$ 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