Question

The following two functions P1 and P2 that share a variable B with an initial value of 22 execute concurrently.

P1() {
    C = B - 1;
    B = 2 * C;
}
P2() {
    D = 2 * B;
    B = D - 1;
}

The number of distinct values that B can possibly take after the execution is _____.

Official answer and solution
Official answer
3
From
Official GATE 2015 answer key

Solution

Trace all valid instruction interleavings of concurrent processes P1 and P2 sharing variable B initialized to 2.

Let initial B=2B = 2.
Process P1 statements:

  • S1S_1: C=B−1C = B - 1
  • S2S_2: B=2∗CB = 2 * C

Process P2 statements:

  • S3S_3: D=2∗BD = 2 * B
  • S4S_4: B=D−1B = D - 1

Tracing possible execution sequences:

  1. P1P1 then P2P2 (S1→S2→S3→S4S_1 \to S_2 \to S_3 \to S_4):
    S1S_1: C=2−1=1C = 2 - 1 = 1.
    S2S_2: B=2×1=2B = 2 \times 1 = 2.
    S3S_3: D=2×2=4D = 2 \times 2 = 4.
    S4S_4: B=4−1=3B = 4 - 1 = 3.
    Final B=3B = 3.

  2. P2P2 then P1P1 (S3→S4→S1→S2S_3 \to S_4 \to S_1 \to S_2):
    S3S_3: D=2×2=4D = 2 \times 2 = 4.
    S4S_4: B=4−1=3B = 4 - 1 = 3.
    S1S_1: C=3−1=2C = 3 - 1 = 2.
    S2S_2: B=2×2=4B = 2 \times 2 = 4.
    Final B=4B = 4.

  3. S1→S3→S4→S2S_1 \to S_3 \to S_4 \to S_2:
    S1S_1: C=2−1=1C = 2 - 1 = 1.
    S3S_3: D=2×2=4D = 2 \times 2 = 4.
    S4S_4: B=4−1=3B = 4 - 1 = 3.
    S2S_2: B=2×C=2×1=2B = 2 \times C = 2 \times 1 = 2.
    Final B=2B = 2.

  4. S3→S1→S2→S4S_3 \to S_1 \to S_2 \to S_4:
    S3S_3: D=2×2=4D = 2 \times 2 = 4.
    S1S_1: C=2−1=1C = 2 - 1 = 1.
    S2S_2: B=2×1=2B = 2 \times 1 = 2.
    S4S_4: B=D−1=4−1=3B = D - 1 = 4 - 1 = 3.
    Final B=3B = 3.

  5. S1→S3→S2→S4S_1 \to S_3 \to S_2 \to S_4:
    S1S_1: C=1,S3C = 1, S_3: D=4D = 4.
    S2S_2: B=2×1=2B = 2 \times 1 = 2.
    S4S_4: B=4−1=3B = 4 - 1 = 3.
    Final B=3B = 3.

  6. S3→S1→S4→S2S_3 \to S_1 \to S_4 \to S_2:
    S3S_3: D=4,S1D = 4, S_1: C=1C = 1.
    S4S_4: B=3B = 3.
    S2S_2: B=2×1=2B = 2 \times 1 = 2.
    Final B=2B = 2.

The distinct final values that BB can take are {2,3,4}\{2, 3, 4\}.
The count of distinct values is 3.

Final answer

3

Common trap

Testing only the two strictly sequential executions (yielding 3 and 4) and overlooking the interleaved case where P1 overwrites B last to leave it at 2.

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

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
19 of 65, printed as CS Q.9
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.