#include #include #include #include /* gcc .... -lpthread */ #include #define CHILDREN 8 /* define three thread states */ #define RUNNING 0 #define DONE 1 #define JOINED 2 int done[ CHILDREN ]; struct thread_data { int t; /* sleep time */ int i; /* index of this thread */ }; void * whattodo( void * arg ); int main() { int i, rc; struct thread_data * t; pthread_t tid[ CHILDREN ]; /* Create threads */ for ( i = 0 ; i < CHILDREN ; i++ ) { done[i] = RUNNING; t = (struct thread_data *)malloc( sizeof( struct thread_data ) ); t->i = i; t->t = 10 + ( rand() % 21 ); /* in range [10,30] */ printf( "MAIN: Next thread will nap for %d seconds.\n", t->t ); rc = pthread_create( &tid[i], NULL, whattodo, t ); if ( rc != 0 ) { perror( "Could not create the thread" ); } } #if 0 /* Wait for threads to terminate */ for ( i = 0 ; i < CHILDREN ; i++ ) { pthread_join( tid[i], NULL ); /* BLOCKING */ } #endif /* NONBLOCKING wait for threads to terminate */ { int c = CHILDREN; while ( c > 0 ) { for ( i = 0 ; i < CHILDREN ; i++ ) { if ( done[i] == DONE ) { pthread_join( tid[i], NULL ); done[i] = JOINED; c--; printf( "MAIN: %d to go.\n", c ); } } sleep( 1 ); /* parent does other work here ... */ } } printf( "MAIN: All threads accounted for.\n" ); return 0; } void * whattodo( void * arg ) { struct thread_data * t = (struct thread_data *)arg; printf( "THREAD %d: I'm gonna nap for %d seconds.\n", pthread_self(), t->t ); sleep( t->t ); printf( "THREAD %d: I'm awake now.\n", pthread_self() ); done[ t->i ] = DONE; return NULL; }