The following two functions P1 and P2 that share a variable B with an initial…

2015

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

image.png

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

Attempted by 229 students.

Show answer & explanation

Correct answer: 3

Final answer: 3 distinct values — 2, 3, and 4.

Explanation: the initial value is B = 2. Depending on the interleaving of reads and writes in the two processes, B can end up as 2, 3, or 4. Representative interleavings are:

  1. P1 runs completely, then P2 runs: P1 computes C = 2 - 1 = 1 and sets B = 2 * 1 = 2. Then P2 computes D = 2 * 2 = 4 and sets B = D - 1 = 3. Final B = 3.

  2. P2 runs completely, then P1 runs: P2 computes D = 2 * 2 = 4 and sets B = 3. Then P1 computes C = 3 - 1 = 2 and sets B = 2 * 2 = 4. Final B = 4.

  3. An interleaving where P1 reads C = B - 1 (C = 1) and is preempted before writing B, then P2 runs fully (making B = 3), and then P1 resumes and writes B = 2 * C = 2. Final B = 2.

Any other interleaving reduces to one of these cases because each read uses either the original B = 2 or the modified B = 3, and the resulting writes can only produce 2, 3, or 4. Therefore there are exactly 3 distinct possible final values.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir