In: Computer Science
Here only a slight change needed to be made to handle the case in which let's say suppose we have 4 philosopher and after each one of them picks their left fork then context switch occurs and we go to next philosopher. that is after philosopher-0 has picked the left fork of index 0 then context switch occurs and we go to philosopher-1 who also captures its left fork i.e. fork 1 and again context switch occurs so in this way switching occurs. so in the ned we will be currently at the philosopher-3 and he would pick its left fork i.e. fork-3 and look for the right fork i.e. fork-0 but this was already picked by the philosopher-0. So the system goes into the deadlock. Here to prevent this situation we just need to change the testing condition for the last philosopher such that he looks for the right fork and after that looks fo left fork. So if this was the case then philosopher-4 instead of picking the leftfork i.e. fork-3 first it will first look for fork-0 but since it is already picked by the philosopher-0 so it will stop. and now the philosopher-2 can continue with its process since fork-3 is still not picked. he puts back fork-2 after eating. So in this way after philosopher-2 , philosopher-1 woulad also complete the task and then philosopher-0. Now after this philosopher-3 can pick the right fork i.e. fork-0 and continue its. task.
void put_fork(int phnum)
{
sem_wait(&mutex);
// state that thinking
state[phnum] = THINKING;
printf("Philosopher %d putting fork %d and %d down\n",
phnum + 1, LEFT + 1, phnum + 1);
printf("Philosopher %d is thinking\n", phnum + 1);
if(phnum==N-1){ // this is the last philosopher for which we reverse the order of checking it will first check right then left
test(RIGHT);
test(LEFT);
}
else{ // this is for the remaining philosopher for which the order of checking will be first check left then right
test(LEFT);
test(RIGHT);
}
sem_post(&mutex);
}