/* philosophers.c dining philosophers using semaphores */ #include #include #include #include #include #include #include #include #define Philosophers 5 int room[2]; /* pipe file descriptors for use as a semaphores */ int frk[Philosophers][2]; void P( int sem[] ){ char buf[1]; read( sem[0], &buf, 1 ); } void V( int sem[] ){ char buf[1] = { 'a' }; write( sem[1], &buf, 1 ); } void *phil( void * arg ) { /* function for each philosopher */ int *me, j; me = (int *) arg; for( j=0; j<3; j++ ) { P( room ); /* enter the room */ P( frk[*me] ); /* acquire the */ P( frk[(*me+1) % Philosophers] ); /* forks */ printf( "Philosopher %d Eating !!\n", *me ); srand( (int)time( NULL ) ); /* eat for between */ sleep((rand() % 15) + 2); /* 2 and 16 seconds */ printf( "Philosopher %d Thinking!!\n", *me ); V( frk[*me] ); /* release the forks */ V( frk[(*me+1) % Philosophers] ); V( room ); /* leave the room */ sleep(rand() % 20); /* think for between 0 and 19 seconds */ } pthread_exit( NULL ); } int main( void ) { int i; pthread_t tid[Philosophers]; int id[Philosophers]; pipe( room ); for( i=0; i