Ex 6 1 Updated Dining Philosophers Problem
Ex 6 1 Updated Dining Philosophers Problem
Dining Philosophers Problem States that there are 5 Philosophers who are engaged in two activities
Thinking and Eating. Meals are taken communally in a table with five plates and five forks in a cyclic
manner as shown in the figure.
Constraints and Condition for the problem :
1. Every Philosopher needs two forks in order to eat.
2. Every Philosopher may pick up the forks on the left or right but only one fork at once.
3. Philosophers only eat when they had two forks. We have to design such a protocol i.e. pre and
post protocol which ensures that a philosopher only eats if he or she had two forks.
4. Each fork is either clean or dirty.
Solution:
Correctness properties it needs to satisfy are:
To solve this Dead Lock situation, Last philosopher (any one can do this) first try to take right side fork
and then left side fork. i.e in our example 5th person tries to take 4th Fork instead of 5th one. Since 4th
Fork already taken by 4th the person, he gets nothing. But he left 5th Fork. Now the first person will take
this 5th Fork and complete dinner and make 1st and 5th available for remaining people. Next 2nd
person takes 1st fork and completes and releases 1st and 2nd. This continuous until all finishes dinner.
1. Mutual Exclusion Principle –
No two Philosophers can have the two forks simultaneously.
2. Free from Deadlock –
Each philosopher can get the chance to eat in a certain finite time.
3. Free from Starvation –
When few Philosophers are waiting then one gets a chance to eat in a while.
4. No strict Alternation.
5. Proper utilization of time.
Algorithm
Program
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5
int main()
{
// Define counter var i and status_message
int i, status_message;
void *msg;
// Wait for all philosophers threads to complete executing (finish dining) before closing the program
for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}
OUTPPUT
Philosopher 2 is thinking
Philosopher 2 is eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 5 is eating
Philosopher 1 is thinking
Philosopher 4 is thinking
Philosopher 4 is eating
Philosopher 2 Finished eating
Philosopher 5 Finished eating
Philosopher 1 is eating
Philosopher 4 Finished eating
Philosopher 3 is eating
Philosopher 1 Finished eating
Philosopher 3 Finished eating