Question

Consider the following multi-threaded code segment (in a mix of C and pseudo-code), invoked by two processes P1 and P2, and each of the processes spawns two threads T1 and T2:

int x = 0; // global
Lock L1; // global

main() {
    create a thread to execute foo(); // Thread T1
    create a thread to execute foo(); // Thread T2
    wait for the two threads to finish execution;
    print(x);
}

foo() {
    int y = 0;
    Acquire L1;
    x = x + 1;
    y = y + 1;
    Release L1;
    print(y);
}

Which of the following statement(s) is/are correct?

Choose every correct option
Official answer and solution
Official answer
A and D
From
Official GATE 2021 answer key

Solution

Distinguish process-level memory isolation from thread-level shared memory and local stack variables.

The program is invoked by two distinct processes, P1P_1 and P2P_2. In standard operating systems:

  • Distinct processes have separate, isolated virtual address spaces. They do not share global variables or lock structures unless explicit shared memory IPC is configured.

Inside each process:

  • The process initializes its own copy of int x = 0; and lock L1.
  • It spawns two threads, T1T_1 and T2T_2, both executing foo().
  • Inside foo(), each thread increments the process-global variable x while holding lock L1. Because the increments are protected by mutex L1, no race condition occurs.
  • Since each process spawns 2 threads and each thread increments x once, x becomes 0+1+1=20 + 1 + 1 = 2 in both P1P_1 and P2P_2.
  • Both P1P_1 and P2P_2 will print x=2x = 2 upon completion. Hence statement A is correct and statement B is incorrect.

Now consider the variable y inside foo():

  • int y = 0; is declared inside foo(), making it a local automatic variable allocated on the private stack of each thread.
  • Each thread has its own private instance of y initialized to 0.
  • Each thread executes y = y + 1; and prints y. The value printed by every thread (T1T_1 and T2T_2 in both P1P_1 and P2P_2) is always 1.
  • Hence statement D is correct and statement C is incorrect.
Final answer

A, D

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

Source

Paper
GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
Question
52 of 65, printed as CS Q.42
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.