This is a interview Question which was asked and wanted to find an efficient solution.
Problem
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.
- the intersection is divided into four quadrants [shown in yellow].
- Cars enter the intersection at random from the four direction [0,1,2,3]
- At the intersection each car can make a single move. the three possible moves are
- Go left
- Go straight
- Go right
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

Semi complete solution
Each quadrant marked in yellow has a semaphore associated with it.
What I imagined was a 2 phase protocol wherein each car would
- get list of quadrants it will pass through
- lock each of the quadrants starting from the last quadrant
- In the above example the car from direction 2 would lock quadrant 0, quadrant 1 and then quadrant 2.
- Move through the intersection
- Release the locks acquired.
- The locks are released in the same order. quadrant 0, quandrant 1 and the quandrant 2
However the above solution is less than optimal as it results in a deadlock.
My Question is
- What other /better way can this be achieved?
- Can I implement this using a semaphore in C?
- If not what synchronization method should I be looking at?
Updates
- I want a solution which allows multiple cars can enter the intersection and still avoid deadlock as well as collision.Having a single lock on the entire intersection would be less than optimized.
I was able to implement a solution in C using the following logic (The actual implementation used semaphores for each of the quadrant).
The solution I mentioned in the question was partially correct however I was experiencing deadlock due to the matter in which locks were made.
I was able to solve the issue by assigning priority to the locks.
The locks are gained by locking highest priority lock first.
Following is a pseudo-code algorithm used by each of the car:
Assumptions:
Algorithm
Each car gets list of quadrants it will pass through
Lock each of the quadrants starting from the quadrant with highest priority.
e.g: In the above example the car from direction 2 taking a left turn would lock quadrant 2, quadrant 0 and then quadrant 1.
Move through the intersection
Release the locks acquired.
e.g: In the above example the locks are released in the same order. quadrant 2, quandrant 1 and the quandrant 0