Skip to content
Official PYQ · 2024

GATE CS 2024 Set 1 Q30 — Processes and Threads

Explain with AI

​​​Consider the following two threads T1\mathrm{T} 1 and T2\mathrm{T} 2 that update two shared variables a\mathrm{a} and b\mathrm{b}. Assume that initially a=b=1\mathrm{a}=\mathrm{b}=1. Though context switching between threads can happen at any time, each statement of  T1\mathrm{T} 1 or  T2\mathrm{T} 2 is executed atomically without interruption.

T1a=a+1; b=b+1;\begin{gathered}\mathrm{T} 1 \\ \mathrm{a}=\mathrm{a}+1; \\ \mathrm{~b}=\mathrm{b}+1;\end{gathered} \quad T2b=2∗b;a=2∗a;\begin{gathered}\mathrm{T} 2 \\ \mathrm{b}=\mathrm {2 * b}; \\ \mathrm{a}=\mathrm 2 * {a}; \end{gathered}

Which one of the following options lists all the possible combinations of values of a and b after both T1 and T2 finish execution?

Choose one option
View worked solution

Answer: A

Let the atomic statements of the two threads be labeled as follows:

  • Thread T1T_1:
    • A1:a=a+1A_1: a = a + 1
    • B1:b=b+1B_1: b = b + 1
  • Thread T2T_2:
    • B2:b=2∗bB_2: b = 2 * b
    • A2:a=2∗aA_2: a = 2 * a

Since the internal statement order within each thread must be preserved, A1A_1 must execute before B1B_1, and B2B_2 must execute before A2A_2. Starting with initial values a=1,b=1a = 1, b = 1, we trace all possible interleavings:

  1. A1→B1→B2→A2A_1 \to B_1 \to B_2 \to A_2:
    • a=1+1=2  ⟹  b=1+1=2  ⟹  b=2×2=4  ⟹  a=2×2=4a = 1 + 1 = 2 \implies b = 1 + 1 = 2 \implies b = 2 \times 2 = 4 \implies a = 2 \times 2 = 4
    • Result: (a=4,b=4)(a = 4, b = 4)
  2. A1→B2→B1→A2A_1 \to B_2 \to B_1 \to A_2:
    • a=2  ⟹  b=2×1=2  ⟹  b=2+1=3  ⟹  a=2×2=4a = 2 \implies b = 2 \times 1 = 2 \implies b = 2 + 1 = 3 \implies a = 2 \times 2 = 4
    • Result: (a=4,b=3)(a = 4, b = 3)
  3. A1→B2→A2→B1A_1 \to B_2 \to A_2 \to B_1:
    • a=2  ⟹  b=2  ⟹  a=2×2=4  ⟹  b=2+1=3a = 2 \implies b = 2 \implies a = 2 \times 2 = 4 \implies b = 2 + 1 = 3
    • Result: (a=4,b=3)(a = 4, b = 3)
  4. B2→A2→A1→B1B_2 \to A_2 \to A_1 \to B_1:
    • b=2×1=2  ⟹  a=2×1=2  ⟹  a=2+1=3  ⟹  b=2+1=3b = 2 \times 1 = 2 \implies a = 2 \times 1 = 2 \implies a = 2 + 1 = 3 \implies b = 2 + 1 = 3
    • Result: (a=3,b=3)(a = 3, b = 3)
  5. B2→A1→A2→B1B_2 \to A_1 \to A_2 \to B_1:
    • b=2  ⟹  a=2  ⟹  a=2×2=4  ⟹  b=2+1=3b = 2 \implies a = 2 \implies a = 2 \times 2 = 4 \implies b = 2 + 1 = 3
    • Result: (a=4,b=3)(a = 4, b = 3)
  6. B2→A1→B1→A2B_2 \to A_1 \to B_1 \to A_2:
    • b=2  ⟹  a=2  ⟹  b=2+1=3  ⟹  a=2×2=4b = 2 \implies a = 2 \implies b = 2 + 1 = 3 \implies a = 2 \times 2 = 4
    • Result: (a=4,b=3)(a = 4, b = 3)

Thus, the only possible final combinations of (a,b)(a, b) are (a=4,b=4)(a=4, b=4), (a=3,b=3)(a=3, b=3), and (a=4,b=3)(a=4, b=3).

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

Published
Report a correction
Keep exploringMore Processes and Threads questions