Question:medium

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? 
 

Show Hint

Global variables are shared among threads of the same process, but not across different processes. Local variables are private to each thread.
Updated On: Feb 2, 2026
  • Both $P1$ and $P2$ will print the value of $x$ as $2$.
  • At least one of $P1$ and $P2$ will print the value of $x$ as $4$.
  • At least one of the threads will print the value of $y$ as $2$.
  • Both $T1$ and $T2$, in both the processes, will print the value of $y$ as $1$.
Show Solution

The Correct Option is A, D

Solution and Explanation

This question involves understanding multi-threaded programming with locks. The key to solving this problem lies in analyzing how the global variable x and the local variable y are affected by the operations in the function foo().

The scenario is as follows:

  • Each process P1 and P2 creates two threads, T1 and T2.
  • The global variable x is shared across all processes and threads.
  • The local variable y is initialized to 0 within the foo() function and is local to the function's instance, thus not shared.

Analyzing the Code Execution:

Step 1: Understanding Lock Mechanism for x

  1. When a thread (either T1 or T2) executes the foo() function, it acquires lock L1 before modifying x.
  2. The lock ensures that only one thread can modify x at a time. Hence, for each process, the increment operation x = x + 1 is atomic for that block of code.
  3. Both T1 and T2 will increment x by 1, so for each process (P1 or P2), x is incremented by 2.
  4. Since processes are independent of each other with regard to x, both P1 and P2 result in x = 2 when they print the final value of x in main().

Step 2: Understanding y's Scope

  1. The variable y is local to the foo() function, meaning each thread has its own instance of y.
  2. Within the foo() function, y is initialized to 0 and then incremented by 1. This means each thread will print y = 1 after its execution.
  3. No thread can affect another thread's local variable y, thus each thread across both processes will print y = 1.

Conclusion:

  • Both P1 and P2 will print the value of x as 2.
  • Both T1 and T2, in both processes, will print the value of y as 1.

These observations rule out the other two options given. Therefore, the correct options are the first and last ones.

Was this answer helpful?
0