CS FundamentalsVery hardProduct company interview · GATE level

Shared int x = 1. Thread T1 executes `x = x + 1;` twice; thread T2 executes `x = x * 2;` once. Each statement compiles to a load of x into a private register, the arithmetic, and a store back to x; only individual loads and stores are atomic. Which set contains exactly the possible final values of x?

  1. A. {4, 6}
  2. B. {2, 3, 4, 5, 6}
  3. C. {3, 4, 5, 6}
  4. D. {2, 3, 4, 5, 6, 8}

Correct answer: B. {2, 3, 4, 5, 6}

Serial orders give 6 (T2 first: 2, 3, 4), 5 (T2 between: 2, 4, 5) and 4 (T2 last: 3, 6). Lost updates add more. If T2 loads 1, T1 does both increments (x = 3) and T2 then stores 2, the result is 2. If T1's first increment loads 1, T2 runs completely (x = 2), and T1 stores 2 and increments to 3, the result is 3. Nothing can exceed 6, since that needs both increments before the doubling. So the set is {2, 3, 4, 5, 6}; 8 would need a value that was never computed.

More Operating Systems questions

Exams that ask this topic