Question

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

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2013 answer key

Solution

Find an interleaving of the four concurrent processes that maximizes the final value of x, leveraging the fact that semaphore S=2 allows two concurrent processes inside the critical region.

Initial conditions:

  • Variable x=0x = 0.
  • Counting semaphore S=2S = 2.
  • Four processes:
    • WW: reads xx, increments by 1, writes xx.
    • XX: reads xx, increments by 1, writes xx.
    • YY: reads xx, decrements by 2, writes xx.
    • ZZ: reads xx, decrements by 2, writes xx.

Each process executes P(S)P(S) before reading xx and V(S)V(S) after storing xx.

Because SS is initialized to 2, two processes can be concurrently inside the critical region. To maximize the final value of xx, we want the decrements by YY and ZZ to be completely overwritten by an increment:

  1. Process WW executes P(S)P(S) (now S=1S = 1). WW reads x=0x = 0 into its local register. WW calculates local value =0+1=1= 0 + 1 = 1, but is preempted before writing back to xx.
  2. Process YY executes P(S)P(S) (now S=0S = 0). YY reads x=0x = 0, computes 0−2=−20 - 2 = -2, writes x=−2x = -2, and executes V(S)V(S) (now S=1S = 1).
  3. Process ZZ executes P(S)P(S) (now S=0S = 0). ZZ reads x=−2x = -2, computes −2−2=−4-2 - 2 = -4, writes x=−4x = -4, and executes V(S)V(S) (now S=1S = 1).
  4. Now process WW resumes. WW writes its computed local value 11 to memory: x=1x = 1. Then WW executes V(S)V(S) (now S=2S = 2). At this point, both decrements from YY and ZZ have been completely overwritten!
  5. Finally, process XX executes sequentially: P(S)P(S) (now S=1S = 1), reads x=1x = 1, computes 1+1=21 + 1 = 2, writes x=2x = 2, and executes V(S)V(S) (now S=2S = 2).

The maximum possible final value of xx is 2.

Final answer

D

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2013 Computer Science and Information Technology (CS)
Question
34 of 65, printed as CS Q.34
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.