Reference no: EM132586050
Assignment -
The local Bridge is undergoing repairs and only one lane is open for traffic. To prevent accidents, traffic lights have been installed at either end of the bridge to synchronize the traffic going in different directions. A car can only cross the bridge if there are no cars going the opposite direction on the bridge. Sensors at either end of the bridge detect when cars arrive and depart from the bridge, and these sensors control the traffic lights.
Below is a skeleton implementation of two routines: Arrive() and Depart(). You may assume that each car is represented by a thread, and threads call Arrive() when they arrive at the bridge and Depart() when they leave the bridge. Threads pass in their direction of travel as input to the routines.
int num_cars = 0;
enum dir = {open, north, south};
dir cur_dir =open;
1. void Arrive (dir my_dir) {
A0: while (cur_dir 1= my_dir I 1 cur_dir 1= open) {
A1: num cars++;
A2: cur dir = my_dir;
2. void Depart (dir my_dir) {
D0: num_cars--;
D1: if (num_cars == 0) {
D2: cur_dir = open;
(a) The code given above does not have any synchronization statements. Outline an execution sequence (referring to the numbered statements) where two threads can cause two cars to travel on the bridge in opposite directions at the same time.
(b) Show how condition variables with explicit locks could be used to correctly synchronize the cars by adding the necessary calls to Condition and Lock operations in the given code with appropriate initializations.
(c) In the corrected codes, show the critical sections.
(d) Can this solution lead to starvation? Briefly explain.