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.

wait (a); count=count+1;
if (count==n) signal (b);
signal(a); wait (b); signal (b);

What does the code achieve??

A.

It ensures that no process executes CODE SECTION Q before every process has finished CODE SECTION P.

B.

It ensures that at most two processes are in CODE SECTION Q at any time.

C.

It ensures that all processes execute CODE SECTION P mutually exclusively.

D.

It ensures that at most n-1 processes are in CODE SECTION P at any time.

Solution:

Given: a = 1, b = 0, count = 0 and n process.

Let n = 3

The given code is : 

Code Section P
1. wait (a);
2. count = count + 1;
3. if (count == n) signal(b);
4. signal(a);
5. wait(b);
6. signal(b);
Code Section Q

Let's say P1 finishes executing section P and enters the given code.

Then :

 

The value of semaphore b remains 0.

P1 gets blocked at line no. 5 because the semaphore b value is already 0 and then we are executing wait(b) on it.

So, P1 will not be able to enter the code section Q.

Now for the second process, all the above-mentioned sequences we will follow.

there count value will become count = 2.

Which is still not equal to the number of processes so, if the loop will not execute again and the value of b remains 0.

Now, the last process will execute line no. 1 and line no. 2. It will make semaphore a = 0 and count = 3.

This time if (count == n) evaluates true and finally signal(b) will execute and make b = 1 for the first time.

Now, the previously blocked process can execute wait(b) and then signal(b) to allow other waiting processes to execute further.

So, following this, all processes enter code section Q after executing code section P.

So, option (A) is correct.

Clearly, Option (B), Option (C), and Option (D) are not correct.