#include #include #include #include /* gcc .... -lpthread */ #include #define CHILDREN 8 void * whattodo( void * arg ); int main() { int i, rc; int * t; pthread_t tid[ CHILDREN ]; /* Create threads */ for ( i = 0 ; i < CHILDREN ; i++ ) { t = (int *)malloc( sizeof( int ) ); *t = 10 + ( rand() % 21 ); /* in range [10,30] */ printf( "MAIN: Next thread will nap for %d seconds.\n", *t ); rc = pthread_create( &tid[i], NULL, whattodo, t ); if ( rc != 0 ) { perror( "Could not create the thread" ); } } /* Wait for threads to terminate */ for ( i = 0 ; i < CHILDREN ; i++ ) { pthread_join( tid[i], NULL ); /* BLOCKING */ } printf( "MAIN: All threads accounted for.\n" ); return 0; } void * whattodo( void * arg ) { int t = *(int *)arg; printf( "THREAD %d: I'm gonna nap for %d seconds.\n", pthread_self(), t ); sleep( t ); printf( "THREAD %d: I'm awake now.\n", pthread_self() ); return NULL; }