Consider the following multi-threaded code segment (in a mix of C and pseudo-code), invoked by two processes and , and each of the processes spawns two threads and :
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?
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 and 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 ) and the lock L1.
- Changes made to
xin have no effect onxin .
2. Thread Sharing within a Process
Threads and spawned by a process share that process's address space, including its global variables.
- For process , both threads and access the same global variable
x. - Since the increment of
xis protected by the lockL1, the operations are mutually exclusive and free from race conditions. - Each thread increments
xby . Since there are two threads, the final value ofxin will be . - Similarly, in process , the two threads increment its independent copy of
x, resulting in a final value of . - Thus, both and will print the value of as . (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 and two in ) has its own independent copy of
y. - Each thread independently initializes its own
yto , increments it to , and prints it. - Thus, all four threads will print the value of
yas . (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.
