Skip to content
Official PYQ · 2015

GATE CS 2015 Set 1 Q9 — Concurrency and Synchronization

Explain with AI
The following two functions P1P1 and P2P2 that share a variable BB with an initial value of 22 execute concurrently.
P1() { P2(){ C = B - 1; D = 2 * B;  B = 2 * C; B = D - 1;}}\begin{array}{|l|l|}\hline \text{P1() \{ } & \text{P2()\{} \\ \text{ C = B - 1;} & \text{ D = 2 * B; } \\ \text{ B = 2 * C;} & \text{ B = D - 1;} \\ \text{\}} & \text{\}} \\ \hline \end{array}
The number of distinct values that BB can possibly take after the execution is______________________.
View worked solution

Answer: 3

Let the instructions of processes P1P1 and P2P2 be labeled as follows:

  • P1:
    • I1I_1: C = B - 1
    • I2I_2: B = 2 * C
  • P2:
    • I3I_3: D = 2 * B
    • I4I_4: B = D - 1

Since CC and DD are local variables and BB is a shared variable (initially B=2B = 2), we can trace all (42)=6\binom{4}{2} = 6 possible concurrent interleavings of these instructions:

  1. I1→I2→I3→I4I_1 \to I_2 \to I_3 \to I_4:
    • I1  ⟹  C=2−1=1I_1 \implies C = 2 - 1 = 1
    • I2  ⟹  B=2×1=2I_2 \implies B = 2 \times 1 = 2
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
  2. I3→I4→I1→I2I_3 \to I_4 \to I_1 \to I_2:
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
    • I1  ⟹  C=3−1=2I_1 \implies C = 3 - 1 = 2
    • I2  ⟹  B=2×2=4I_2 \implies B = 2 \times 2 = 4
  3. I1→I3→I2→I4I_1 \to I_3 \to I_2 \to I_4:
    • I1  ⟹  C=2−1=1I_1 \implies C = 2 - 1 = 1
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I2  ⟹  B=2×1=2I_2 \implies B = 2 \times 1 = 2
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
  4. I1→I3→I4→I2I_1 \to I_3 \to I_4 \to I_2:
    • I1  ⟹  C=2−1=1I_1 \implies C = 2 - 1 = 1
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
    • I2  ⟹  B=2×1=2I_2 \implies B = 2 \times 1 = 2
  5. I3→I1→I2→I4I_3 \to I_1 \to I_2 \to I_4:
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I1  ⟹  C=2−1=1I_1 \implies C = 2 - 1 = 1
    • I2  ⟹  B=2×1=2I_2 \implies B = 2 \times 1 = 2
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
  6. I3→I1→I4→I2I_3 \to I_1 \to I_4 \to I_2:
    • I3  ⟹  D=2×2=4I_3 \implies D = 2 \times 2 = 4
    • I1  ⟹  C=2−1=1I_1 \implies C = 2 - 1 = 1
    • I4  ⟹  B=4−1=3I_4 \implies B = 4 - 1 = 3
    • I2  ⟹  B=2×1=2I_2 \implies B = 2 \times 1 = 2

The set of distinct values that BB can take after execution is {2,3,4}\{2, 3, 4\}. Thus, there are 3 distinct values.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Concurrency and Synchronization questions