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?
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:
foo() function and is local to the function's instance, thus not shared.Step 1: Understanding Lock Mechanism for x
foo() function, it acquires lock L1 before modifying x.main().Step 2: Understanding y's Scope
foo() function, meaning each thread has its own instance of y.foo() function, y is initialized to 0 and then incremented by 1. This means each thread will print y = 1 after its execution.These observations rule out the other two options given. Therefore, the correct options are the first and last ones.
Consider the following threads, T1, T2, and T3 executing on a single processor, synchronized using three binary semaphore variables, S1, S2, and S3, operated upon using standard wait() and signal(). The threads can be context switched in any order and at any time.
