#include #include #include /* use -lpthread or -pthread on the gcc line */ #include /* global mutex variable */ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #define CHILDREN 8 void * whattodo( void * arg ); int main() { pthread_t tid[ CHILDREN ]; /* keep track of the thread IDs */ int i, rc; int * t; for ( i = 0 ; i < CHILDREN ; i++ ) { t = (int *)malloc( sizeof( int ) ); #if 0 *t = 2 + i * 2; /* 2, 4, 6, 8, 10 */ #endif *t = 20 - (2 + i * 2); 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 critical_section( int t ) { printf( "THREAD %u: Entering critical section\n", (unsigned int)pthread_self() ); sleep( t ); printf( "THREAD %u: Leaving critical section\n", (unsigned int)pthread_self() ); } void * whattodo( void * arg ) { int t = *(int *)arg; printf( "THREAD %u: I'm gonna nap for %d seconds.\n", (unsigned int)pthread_self(), t ); pthread_mutex_lock( &mutex ); /* get the lock */ critical_section( t ); pthread_mutex_unlock( &mutex ); /* release the lock */ printf( "THREAD %u: I'm awake now.\n", (unsigned int)pthread_self() ); return NULL; /* pthread_exit() */ }