Each of a set of n processes executes the following code using two semaphores a and b initialized to 1 and 0, respectively. Assume that count is a shared variable initialized to 0 and not used in CODE SECTION P. CODE SECTION P wait (a); count=count+1 ; if (count==n) signal (b) ; signal (a) ; wait (b) ; signal (b) ; CODE SECTION Q What does the code achieve?

Each of a set of n processes executes the following code using two semaphores a and b initialized to 1 and 0, respectively. Assume that count is a shared variable initialized to 0 and not used in CODE SECTION P. CODE SECTION P wait (a); count=count+1 ; if (count==n) signal (b) ; signal (a) ; wait (b) ; signal (b) ; CODE SECTION Q What does the code achieve? Correct Answer It ensures that no process executes CODE SECTION Q before every process has finished CODE SECTION P.

Explanation:

The key statement in the above code is wait (b). It will keep the remaining processes blocked until value on count becomes n. Once, the value of count = n, signal (b) would be executed and then a process can enter the code section Q. Thus, none of the process will execute Q until every process has executed code section P.

Stepwise Explanation:

Initialization:  a=1, b=0, count= 0

There are n processes say, P1, P2, P3, ……………., Pn.

Let’s assume P1 has executed successfully the code section P and encounters the statements:

wait (a);      

Now, ‘a’ becomes 0, so all the subsequent processes are blocked.

b= 0, count= 0.

count=count+1 ;                          

if (count==n) signal (b) ;             

signal (a);                                        

wait (b) ;                                

signal (b);                             

This statement would only run if its preceding statement is executed, which in turn would only be executed if (count==n). Therefore, none of the process would execute Q until every process has successfully executed code section P.

Related Questions