Consider the following multi-threaded code segment (in a mix of C and pseudocode), 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 ?

Consider the following multi-threaded code segment (in a mix of C and pseudocode), 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 ? Correct Answer Both T1 and T2, in both the processes, will print the value of y as 1., Both P1 and P2 will print the value of x as 2.

Answer: Option 1 and Option 3.

Explanation:

Option 1:  Both T1 and T2, in both the processes, will print the value of y as 1.

This Option is Correct. Since Every thread makes a new temporary variable (y) and then it increments y in mutually exclusive fashion.

Option 2: At least one of P1 and P2 will print the value of x as 4.

This Option is not correct. x=4 is not possible.

Option 3:Both P1 and P2 will print the value of x as 2.

This Option is correct. 

each process, two threads are created and they increment variable x after acquiring the lock L1.So no interleaving execution of increment statement possible.

Print(x) will be performed when both threads complete execution. Hence both the process will print x as 2 only.

Option 4:At least one of the threads will print the value of y as 2.

This Option is not correct. because both threads have a different copy of y variable in their memory even one thread increment variable it will reflect in its own memory, not in the other thread's memory. so y = 2 not possible.

Related Questions