Consider the following multi-threaded code segment (in a mix of C and…
2021
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?
Answer: A. Both P1 and P2 will print the value of x as 2.; D. Both T1 and T2, in both the processes, will print the value of y as 1. — Final answer: Both processes will print x = 2, and every thread will print y = 1. Per-process global x: Each process starts with x = 0 and creates two threads…
- A.
Both P1 and P2 will print the value of x as 2.
- B.
At least of P1 and P2 will print the value of x as 4.
- C.
At least one of the threads will print the value of y as 2.
- D.
Both T1 and T2, in both the processes, will print the value of y as 1.
Attempted by 75 students.
Show answer & explanation
Correct answer: A, D
Final answer: Both processes will print x = 2, and every thread will print y = 1.
Per-process global x: Each process starts with x = 0 and creates two threads that run foo. Each thread increments x once while holding the lock. Therefore, within a process x is incremented twice and becomes 2.
Process isolation: Processes have separate address spaces by default. That means P1 and P2 do not share the same x or the same lock unless explicit shared memory is used. Hence each process prints its own x = 2, not a combined 4.
Local variable y: y is allocated afresh for each foo invocation (per thread) and initialized to 0. Each thread executes y = y + 1 exactly once and then prints y, so every thread prints 1.
Conclusion: The correct statements are the ones that state each process prints x = 2 and each thread prints y = 1.
A video solution is available for this question — log in and enroll to watch it.