I understand question 1 but I am having trouble with number 2. (a) Given the fol
ID: 3844656 • Letter: I
Question
I understand question 1 but I am having trouble with number 2.
(a) Given the following solution for the critical section problem for two processes (the code shown is for processes Pi), show why it does not satisfy the mutual exclusion requirement. Here, turn, flag[i], and flag[j] are is shared variables; flag[i] and flag[j] are initialized to FALSE and turn initialized to i. do {flag[i] = true; turn = i; while (flag[i] && turn == j); Critical section flag[i] = FALSE; Remainder section} (b) What happens if flag[i] and flag[j] are set to TRUE in the above code? Three processes P1, P2, and P3 are sharing a resource R1 in a mutually exclusive manner. Using test_and_set instruction, show code for P1, P2, and P3 that shows the entry section and exit section (similar to the code shown in Question 1). Using this code, show a scenario if all three processes want to enter their critical sections.Explanation / Answer
function Lock(boolean_ref lock) {
while (test_and_set(lock) == true);
}
function TestAndSet(boolean_ref lock) {
boolean initial = lock;
lock = true;
return initial;
}
The function TestAndSet is atomic and process cannot be preempted during TestAndSet
Suppose P1, P2, P3 wants to access R1 at the same time. For accessing R1, the process must have the lock.
We know that when the Recouce is not locked, the lock value of the resource is 'false'
P1, P2, P3 calls Lock(R1_lock) to lock the resouce R1. But mutual exclusion property will allow only one process to gain access.
In our case let it be Process P2
P2:
Lock (R1_lock) {
while (TestAndSet(R1_lock) == true);
critical section
R1_lock = false;
}
Since Initial value of lock was fasle,
TestAndSet(R1_lock) will return false and while loop will terminate and the process will not busy wait and it will also update lock to 'true'.
At this time, when other processes try to lock R1_lock, TestAndSet(R1_lock) will return true and while loop will not terminate and the process continue to busy wait. This will happen untill Procsess P2 manually sets R1_flag to false or unlock it.
Once unlocked, either P1 or P3 can gain access to R1 while the other have to busy wait.
This ensures Mutual Exclusion