Example: The dining-philosophers problem
There is a condition that all the philosophers pick up the chopsticks on the left at the beginning. Then all the philosophers try to pick up the chopsticks on the right which are all being occupied. So all the philosophers cannot pick up the chopsticks on the right buy need to wait for chopsticks released by other philosophers. As a result, all five ( one philosophers maps to a thread ) threads are waiting to be woken up by another process and are locked, a deadlock occurs.
a. Four necessary conditions for deadlock in this situation:
- Mutual exclusion: only one philosopher (process) at a time can use the chopstick (resource). If another process requests that chopstick, he/she must wait until the chopsticks be released.
- Hold and wait: In this situation, all philosopher are holding one chopstick which is being occupied by other philosophers.
- No preemption: The chopsticks cannot be preempted. A chopstick can be released only voluntarily by the philosopher holding it.
- Circular wait: Suppose a set {P0, P1, P2, P3, P4} of philosophers, in this situation, Pi is waiting Pi+1 (i = 0, 1, 2, 4) to release the chopstick that requests and P4 is waiting for P0. A circular waiting exits.
b. Simple solution:
Refer to the semaphore mechanism, which allows only four philosophers to pick up chopsticks on the same side at the same time (set the semaphore and initialize it with a value of 4). This ensures that one philosopher will be able to pick up two chopsticks to finish eating and release resources for other philosophers to use.