/* ---------------------------------------------------------------- */ /* philo.c: */ /* This is a naive version of the philosopher problem. It could */ /* deadlock. */ /* ---------------------------------------------------------------- */ #include #include #include "mtuThread.h" #define PHILOSOPHERS 5 /* number of philosophers */ int Iteration; /* the # of eat-think cycles*/ MUTEX_t Chopstick[PHILOSOPHERS]; /* protect chopsticks */ /* ---------------------------------------------------------------- */ /* SimulatedDelay(): */ /* This function simulates a delay by executing THREAD_YIELD() */ /* a random number of times. */ /* ---------------------------------------------------------------- */ void SimulatedDelay(void) { int RandomTimes; int i; RandomTimes = rand() % 5; /* you can use other numbers*/ for (i = 1; i <= RandomTimes; i++) THREAD_YIELD(); } /* ---------------------------------------------------------------- */ /* Philosopher(): */ /* Simulates one philosopher. */ /* ---------------------------------------------------------------- */ void Philosopher(int No) { int Left, Right; int RandomTimes; char spaces[PHILOSOPHERS*2+1]; int i, j; Left = No; Right = (No + 1) % PHILOSOPHERS; for (i = 0; i < 2*No; i++) /* build leading spaces */ spaces[i] = ' '; spaces[i] = '\0'; printf("%sPhilosopher %d starts\n", spaces, No); for (i = 0; i < Iteration; i++) { printf("%sPhilosopher %d is thinking\n", spaces, No); SimulatedDelay(); /* think for a while */ MUTEX_LOCK(Chopstick[Left]); /* take 'left' chopstick */ MUTEX_LOCK(Chopstick[Right]); /* take 'right' chopstick */ printf("%sPhilosopher %d gets chopsticks and eats\n", spaces, No); SimulatedDelay(); /* eat for a while */ printf("%sPhilosopher %d finishes eating\n", spaces, No); MUTEX_UNLOCK(Chopstick[Left]); /* release 'left' chop */ MUTEX_UNLOCK(Chopstick[Right]); /* release 'right' chop*/ } THREAD_EXIT(); } /* ---------------------------------------------------------------- */ /* The main program */ /* ---------------------------------------------------------------- */ int main(int argc, char *argv[]) { int SeatNo[PHILOSOPHERS]; THREAD_t Philosophers[PHILOSOPHERS]; int i; if (argc != 2) { printf("Please input the number of iterations.\n"); exit(0); } else Iteration = abs(atoi(argv[1])); srand((unsigned int)time(NULL)); /* initialize random number */ for (i = 0; i < PHILOSOPHERS; i++) /* create mutex locks */ Chopstick[i]= MUTEX_INIT(); for (i = 0; i < PHILOSOPHERS; i++) { /* create philosophers */ SeatNo[i] = i; /* philosopher number */ Philosophers[i] = /* create a thread */ THREAD_CREATE(Philosopher, /* the thread function */ THREAD_SIZE, /* stack size */ THREAD_NORMAL, /* thread flag */ SeatNo[i], /* play a trick here */ (char **)0); /* no argument list */ if (Philosophers[i] == (THREAD_t)mtu_ERROR) { /* if failed*/ printf("Thread creation failed.\n"); /* exit */ exit(0); } } for (i=0; i