Skip to content
Official PYQ · 2021

GATE CS 2021 Set 2 Q42 — Processes and Threads

Explain with AI

​​​​​​Consider the following multi-threaded code segment (in a mix of C and pseudo-code), invoked by two processes P1P_1 and P2P_2, and each of the processes spawns two threads T1T_1 and T2T_2:

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?

Select all correct options
View worked solution

Answer: A;D

To determine the correct statements, let us analyze how processes and threads manage memory and variables:

1. Process Isolation (Independent Address Spaces)

Processes P1P_1 and P2P_2 run in completely separate address spaces. Therefore, they do not share global variables. Each process has its own independent copy of the global variable x (initialized to 00) and the lock L1.

  • Changes made to x in P1P_1 have no effect on x in P2P_2.

2. Thread Sharing within a Process

Threads T1T_1 and T2T_2 spawned by a process share that process's address space, including its global variables.

  • For process P1P_1, both threads T1T_1 and T2T_2 access the same global variable x.
  • Since the increment of x is protected by the lock L1, the operations are mutually exclusive and free from race conditions.
  • Each thread increments x by 11. Since there are two threads, the final value of x in P1P_1 will be 0+1+1=20 + 1 + 1 = 2.
  • Similarly, in process P2P_2, the two threads increment its independent copy of x, resulting in a final value of 22.
  • Thus, both P1P_1 and P2P_2 will print the value of xx as 22. (Option A is correct, Option B is incorrect)

3. Local Variables and Thread Stacks

The variable y is declared inside the function foo() as a local variable (int y = 0;).

  • Every thread has its own private stack where its local variables are allocated.
  • Therefore, each of the four threads (two in P1P_1 and two in P2P_2) has its own independent copy of y.
  • Each thread independently initializes its own y to 00, increments it to 11, and prints it.
  • Thus, all four threads will print the value of y as 11. (Option D is correct, Option C is incorrect)

Conclusion

The correct options are A and D.

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

Published
Report a correction
Keep exploringMore Processes and Threads questions