Question: Dining Philosophers problem is a famous problem in OS2. A deadlock may happen when all philosophers want to start eating at the same time and

Dining Philosophers problem is a famous problem in OS2. A deadlock may happen when all philosophers want to start eating at the same time and pick up one chopstick and wait for the other chopstick. We can use semaphores to simulate the availability of chopsticks.

To prevent the deadlock; we have discussed this solution:

1. Allow a philosopher to pick up her chopsticks only if both are available.

Based on the program, please implement the above solution to prevent the deadlock.

#include

#include

#include

#define N 5 //the number of philosophers

sem_t S[N]; //semaphores for chopsticks

void * philospher(void *num);

void take_chopsticks(int);

void put_chopsticks(int);

int phil_num[N]={0,1,2,3,4}; //philosopher ID

int main()

{

int i;

pthread_t thread_id[N];

for(i=0;i

sem_init(&S[i],0,1);

for(i=0;i

pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);

for(i=0;i

pthread_join(thread_id[i],NULL);

}

void *philospher(void *num)

{

while(1)

{

int *i = num;

take_chopsticks(*i);

put_chopsticks(*i);

}

}

void take_chopsticks(int ph_num)

{

printf("Philosopher %d is Hungry ",ph_num);

sem_wait(&S[ph_num]); //take the left chopstick

printf("Philosopher %d takes chopstick %d ",ph_num, ph_num);

sleep(1);

sem_wait (&S[(ph_num+1)%N]); //take the right chopstick

printf("Philosopher %d takes chopstick %d ",ph_num,(ph_num+1)%N);

printf("Philosopher %d is eating ",ph_num);

sleep(1);

}

void put_chopsticks(int ph_num)

{

sem_post (&S[ph_num]); //put the left chopstick

printf("Philosopher %d putting chopstick %d ",ph_num, ph_num);

sleep(1);

sem_post (&S[(ph_num+1)%N]); //put the right chopstick

printf("Philosopher %d putting chopstick %d ",ph_num,(ph_num+1)%N);

printf("Philosopher %d is thinking ",ph_num);

sleep(1);

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!