3.8 Suppose your machine has the following atomic instruction: flip (lock) (lock = (lock + 1 ) % 2; # flip the lock return (lock); > # return the new value Someone suggests the following solution to the critical section problem for tw processes: int lock = 0; # shared variable process CS[i = 1 to 2] { while (true) { } } while (flip (lock) != 1) while (lock != 0) skip; critical section; lock = 0; noncritical section; Exercises 145 (a) Explain why this solution will not work-in other words, give an execution order that results in both processes being in their critical sections at the same time. (b) Suppose that the first line in the body of flip is changed to do addition module 3 rather than modulo 2. Will the solution now work for two processes? Explain your answer.
The question is in the image
a)This will not work for two processes because say there are two processes P1 and P2 and initially lock is 0.
When P1 executes flip(lock) in the outer while loop the value of lock becomes 1, and as the while statement becomes false(as lock == 1) , therefore, P1 will come out of the while loop and start executing in the critical section.
Now say P2 comes and executes flip(lock) in the outer while loop.The value returned by flip(lock) now will be 0.As the outer loop condition is true it will come to the inner while loop and execute it.In the inner while loop (as lock == 0) it will come out and again execute outer while loop.Now when P2 executes the outer while loop again the value of flip(lock) will be returned as 1.Now as the while statement becomes false(as lock==1) , therefore it will come out of the while loop and start executing in the critical section.
Therefore there will be two process running in the critical section P1 and P2.(no mutual exclusion guaranteed).
Trending now
This is a popular solution!
Step by step
Solved in 2 steps