Barrier is a synchronization construct where a set of processes synchronizes…

2006

Barrier is a synchronization construct where a set of processes synchronizes globally i.e. each process in the set arrives at the barrier and waits for all others to arrive and then all processes leave the barrier. Let the number of processes in the set be three and S be a binary semaphore with the usual P and V functions. Consider the following C implementation of a barrier with line numbers shown on left.

void barrier (void) {

1: P(S);

2: process_arrived++;

3. V(S);

4: while (process_arrived !=3);

5: P(S);

6: process_left++;

7: if (process_left==3) {

8: process_arrived = 0;

9: process_left = 0;

10: }

11: V(S);

}

The variables process_arrived and process_left are shared among all processes and are initialized to zero. In a concurrent program all the three processes call the barrier function when they need to synchronize globally. Which one of the following rectifies the problem in the implementation?

  1. A.

    Lines 6 to 10 are simply replaced by process_arrived

  2. B.

    At the beginning of the barrier the first process to enter the barrier waits until process_arrived becomes zero before proceeding to execute P(S).

  3. C.

    Context switch is disabled at the beginning of the barrier and re-enabled at the end.

  4. D.

    The variable process_left is made private instead of shared

Attempted by 12 students.

Show answer & explanation

Correct answer: B

The provided implementation has a race condition where new processes can enter the barrier before previous ones reset shared variables. Specifically, there is no check to ensure process_arrived is zero before a new cycle begins. This allows overlapping cycles where counters are incremented while being reset, leading to incorrect synchronization or deadlock. To rectify this, the first process to arrive must verify that process_arrived is zero before proceeding. If it is not, the process waits until all previous processes have finished and reset the counters to zero. This ensures a clean state for each synchronization cycle.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir