This is a interview Question which was asked and wanted to find an efficient solution.
Consider a intersection of four roads as shown in the diagram. Each road is defined to have a direction. How would you solve the problem so as to improve the traffic condition and avoid deadlocks.
e.g :
if a car enters from direction 2 and wants to take a left turn. it should pass through quandrant 2 , quandrant 1 and finally quandrant 0

Each quadrant marked in yellow has a semaphore associated with it. What I imagined was a 2 phase protocol wherein each car would
However the above solution is less than optimal as it results in a deadlock.
Your solution (as suggested in step 2) does not avoid deadlock.
Consider the case when from the four streets there are cars wanting to turn to their left. Then all the cars start locking different cuadrants:
from direction 0, it locks cuadrant 2. from direction 1, it locks cuadrant 3. from direction 2, it locks cuadrant 0. from direction 3, it locks cuadrant 1. -- deadlock --
You could avoid the deadlock by having a mutex shared by the four directions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With