Dining Philosopher's problem

bshap0624
homework_2_4.c

#include<stdio.h> #include<semaphore.h> #include<pthread.h> #define N 5 #define LEFT (i+4)%N #define RIGHT (i+1)%N #define THINKING 0 #define HUNGRY 1 #define EATING 2 typedef int semaphore; //semaphores are a special kind of int semaphore state[N]; //array to keep track of everyone's state semaphore mutex = 1; //mutual exclusion for critical regions semaphore S[N]; //one semaphore per philosopher void * philospher(); void take_fork(); void put_fork(); void test(); int main() { pthread_t p1,p2,p3,p4,p5; sem_init(&mutex,0,1); sem_init(&S[0],0,0); sem_init(&S[1],0,0); sem_init(&S[2],0,0); sem_init(&S[3],0,0); sem_init(&S[4],0,0); pthread_create(&p1,NULL,philospher,0); pthread_create(&p2,NULL,philospher,1); pthread_create(&p3,NULL,philospher,2); pthread_create(&p4,NULL,philospher,3); pthread_create(&p5,NULL,philospher,4); pthread_join(p1,NULL); pthread_join(p2,NULL); pthread_join(p3,NULL); pthread_join(p4,NULL); pthread_join(p5,NULL); } void *philospher(int i) { while(1) { sleep(1); take_fork(i); sleep(0); put_fork(i); } } void take_fork(int i) { sem_wait(&mutex); state[i] = HUNGRY; printf("Philosopher %d is Hungry\n",i+1); test(i); sem_post(&mutex); sem_wait(&S[i]); sleep(1); } void test(int i) { if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; sleep(2); printf("Philosopher %d takes fork %d and %d \n",i+1,LEFT+1,i+1); printf("Philosopher %d is Eating\n",i+1); sem_post(&S[i]); } } void put_fork(int i) { sem_wait(&mutex); state[i] = THINKING; printf("Philosopher %d putting fork %d and %d down\n",i+1,LEFT+1,i+1); printf("Philosopher %d is thinking\n",i+1); test(LEFT); test(RIGHT); sem_post(&mutex); }