/* From smart@nu Sun Oct 3 16:01:12 1993 Date: Sun, 3 Oct 1993 16:00:39 -0400 (EDT) */ /******************************************************************* Programmer: Todd Smart (237-31-1359) Date: 9/30/93 Assignment: Program #1 for COP 4610 Description: This program solves the Dining Philosopher's problem as specified in the text. Note: much of this program was taken from examples in the text (as suggested). *******************************************************************/ #define _XOPEN_SOURCE 500 #define _REENTRANT #include #include #include #include "chopsticks.h" #define N 5 /*number of philosophers*/ #define LEFT (i+N-1)%N /*philo to the left*/ #define RIGHT (i+1)%N /*philo to the right*/ #define THINKING 1 /*assign values to states*/ #define HUNGRY 2 #define EATING 3 pthread_cond_t chopstick_cond[N]; /*one condition per philosopher*/ pthread_mutex_t lock; /*critical regions mutual exclusion*/ int state[N]; /*state of each philosopher*/ int test(int); /*declare test routine*/ /* CHOPSTICKS_INIT initializes the program */ void chopsticks_init() { int i; pthread_mutex_init(&lock, NULL); for (i = 0; i < N; i++) { pthread_cond_init(&chopstick_cond[i], NULL); state[i] = THINKING; } } /* CHOPSTICKS_TAKE performs the following: it will lock the mutex, change the state of the philosopher to hungry, and let him attempt to eat. If the philosopher can eat, his state is changed to EATING. If the philosopher can not eat, he is blocked until a neighbor puts down its sticks. */ void chopsticks_take(i) int i; { pthread_mutex_lock(&lock); /* enter cs, lock mutex */ state[i] = HUNGRY; /* set philosopher's state to HUNGRY */ test(i); /* test philosopher */ while (state[i] == HUNGRY) /* loop while philosopher is hungry */ pthread_cond_wait(&chopstick_cond[i],&lock); pthread_mutex_unlock(&lock); /* exit cs, unlock mutex */ } /* CHOPSTICKS_PUT performs the following: change state of philosopher to THINKING, test if the neighbors of the philosopher can eat. If they can eat change their state to EATING. */ void chopsticks_put(i) int i; { pthread_mutex_lock(&lock); /* enter cs, lock mutex */ state[i] = THINKING; test(LEFT); /* test neighbors */ test(RIGHT); pthread_mutex_unlock(&lock); /* exit cs, unlock mutex */ } /* TEST is the same routine as found in the text book on Pg. 58. It checks to see if the state of the philosopher is HUNGRY and that his neighbors aren't eating. */ int test(i) int i; { if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; pthread_cond_signal(&chopstick_cond[i]); } return 0; }