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?
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, and . 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 lockL1. - It spawns two threads, and , both executing
foo(). - Inside
foo(), each thread increments the process-global variablexwhile holding lockL1. Because the increments are protected by mutexL1, no race condition occurs. - Since each process spawns 2 threads and each thread increments
xonce,xbecomes in both and . - Both and will print upon completion. Hence statement A is correct and statement B is incorrect.
Now consider the variable y inside foo():
int y = 0;is declared insidefoo(), making it a local automatic variable allocated on the private stack of each thread.- Each thread has its own private instance of
yinitialized to 0. - Each thread executes
y = y + 1;and printsy. The value printed by every thread ( and in both and ) is always 1. - Hence statement D is correct and statement C is incorrect.
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.