GATE - 2013 | OS | A shared variable x, initialized to zero, is operated on by four concurrent

GATE - 2013 | OS | A shared variable x, initialized to zero, is operated on by four concurrent
Posted on 12-02-2022

GATE - 2013 [Operating System]

Question:

A shared variable x, initialized to zero, is operated on by four concurrent processes W, X, Y, Z as follows. Each of the processes W and X reads x from memory, increments by one, stores it to memory, and then terminates. Each of the processes Y and Z reads x from memory, decrements by two, stores it to memory, and then terminates. Each process before reading x invokes the P operation (i.e., wait) on a counting semaphore S and invokes the V operation (i.e., signal) on the semaphore S after storing x to memory. Semaphore S is initialized to two. What is the maximum possible value of x after all processes complete execution?

A

-2

B

-1

C

1

D

2

    

Solution:

Option (D) is Correct.

A shared variable x, initialized to zero, is operated on by four concurrent processes W, X, Y, Z as follows. Each of the processes W and X reads x from memory, increments by one, stores it to memory, and then terminates. Each of the processes Y and Z reads x from memory, decrements by two, stores it to memory, and then terminates. Each process before reading x invokes the P operation (i.e., wait) on a counting semaphore S and invokes the V operation (i.e., signal) on the semaphore S after storing x to memory. Semaphore S is initialized to two. What is the maximum possible value of x after all processes complete execution?


Suppose, 'W' executes first, and makes the value of semaphore S=1.

Now it increments the value of x to 1 and comes out and makes S=2.

Now 'X' executes, where the value of x=1 is stored in R1 and then R1 is incremented and the value in R1 is 2.

Now, 'X' gets preempted.

Also to be noted that the value of semaphore S is now '1' because the execution during process X got preempted and wasn't able to increase the value of S to 2.


Now, process Y will get completely executed and then Z will get completely executed.

Now the value of 'x' is -3.

Now again 'X' will get executed and the value stored in R1 i.e., '2' will get stored in 'x'.

So the value in 'x' will be finally 2.


So the maximum possible value of 'x' is 2.

Thank You