The Dining Philosophers Problem and Solution

What is the Dining Philosophers' problem?

In the Dining Philosophers problem, we have a table where five philosophers are sitting, with a bowl of noodles in the center. Each philosopher has a plate and a fork, totaling five forks. The philosophers spend their time either eating or thinking—they don't do anything else or communicate with each other.
To eat, a philosopher needs to use two forks, one on each side. The issue arises if all five philosophers try to eat at the same time; they would need a total of 10 forks, but only 5 are available. This could lead to a deadlock, where no philosopher can proceed because each is waiting for a fork that another philosopher is holding.
To prevent this deadlock, we use semaphores. Each fork is treated as a binary semaphore. In this scenario, each philosopher represents a process, and the forks represent resources. By carefully managing the semaphores, we can avoid the deadlock and ensure that the philosophers can take turns eating.

The solution to the problem
  • Wait for the First Fork: When philosopher i wants to eat, they first call wait(fork[i]). This checks if the fork on their left (fork i) is available. If it is, they pick it up (acquire the fork).
  • Wait for the Second Fork: Next, they call wait(fork[(i+1)%5]). This checks if the fork on their right (fork [(i+1)%5]) is available. If it is, they pick it up.
  • Eat: Once both forks are acquired, the philosopher can eat.
  • Signal After Eating: After finishing their meal, the philosopher releases both forks by calling signal(fork[i]) and signal(fork[(i+1)%5]), making them available for other philosophers.

The issue with this solution is that if all philosophers pick up one fork at the same time, a deadlock situation will occur. Each philosopher will be stuck waiting for the second fork, leading to an infinite loop where no one can eat. 
  • Reduce the Number of Philosophers to 4: By allowing only 4 philosophers to sit at the table instead of 5, there will always be at least one fork available for a philosopher to pick up. This prevents a situation where all philosophers are waiting for the other fork, thus avoiding a deadlock.
  • Place Lock: The second solution is to place a lock on the process of picking up both forks simultaneously. This ensures that a philosopher can only proceed if both forks are available at the same time, preventing the deadlock situation where each philosopher is waiting indefinitely for the second fork.
  • Odd-even rule: an odd philosopher picks up his left fork then his right fork and the even philosopher picks up her right fork then her left fork.





Comments

Post a Comment

Popular posts from this blog

Indexed allocation

Thrashing

Basics of paging