/* philosophers.c dining philosophers using semaphores */ #include #include #include #include #include #include #include #include #include "simphil.h" #define Philosophers 5 void cleanup( void ) { /* removes semaphores */ rm_sem( forks ); printf( "end of cleanup\n" ); exit(1); } void *phil( void * arg ) { /* function for each philosopher */ int *me, j; me = (int *) arg; for( j=0; j<3; j++ ) { /* acquire the */ SimOps( forks, *me, (*me+1) % 5, -1 ); /* forks */ printf( "Philosopher %d Eating !!\n", *me ); srand( time( NULL ) ); /* eat for between */ sleep((rand() % 15) + 2); /* 2 and 16 seconds */ printf( "Philosopher %d Thinking!!\n", *me ); /* release the forks */ SimOps( forks, *me, (*me+1) % 5, 1 ); 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]; union semun { int val; struct semid_ds *buf; ushort *array; } arg; set_the_table(); /* establish the sem set */ arg.val = 1; for( i=0; i