#include #include #include /* use -lpthread or -pthread on the gcc line */ #include #define CHILDREN 8 void * whattodo( void * arg ); int main() { pthread_t tid[ CHILDREN ]; /* keep track of the thread IDs */ int i, rc; #if 0 int * t; #endif for ( i = 0 ; i < CHILDREN ; i++ ) { #if 0 t = (int *)malloc( sizeof( int ) ); *t = 2 + i * 2; /* 2, 4, 6, 8, 10 */ *t = 20 - (2 + i * 2); #endif /* we can't rely on this local variable being synchronized */ int t = 2 + i * 2; /* 2, 4, 6, 8, 10 */ printf( "MAIN: Next thread will nap for %d seconds.\n", t ); rc = pthread_create( &tid[i], NULL, whattodo, &t ); if ( rc != 0 ) { perror( "MAIN: Could not create child thread" ); } } /* wait for threads to terminate */ for ( i = 0 ; i < CHILDREN ; i++ ) { pthread_join( tid[i], NULL ); printf( "MAIN: Joined a child thread.\n" ); } printf( "MAIN: All threads successfully joined.\n" ); return 0; } void * whattodo( void * arg ) { int t = *(int *)arg; printf( "THREAD %u: I'm gonna nap for %d seconds.\n", (unsigned int)pthread_self(), t ); sleep( t ); printf( "THREAD %u: I'm awake now.\n", (unsigned int)pthread_self() ); return NULL; /* pthread_exit() */ }