I am trying to understand the peterson's solution for synchronisation. For reference, I am attaching the source of reading:
This is from the wikipedia page. Now,
Let's say P1 wants to enter the critical section. It sets flag1 = true
and turn=0
. If P0 is already in its critical section, P1 will continuously wait in its while loop while(flag[0] == true && turn ==0)
as flag[0] = true
.
My doubt is:
flag[0] = true
. Due to some reason, it couldnt't execute the next line and terminated. In this, flag[0] is also true and
turn is also 0. P1 unnecessarily waits while no process is inside
the critical section. turn
variable. Why not only this: while(flag[0]== true)
As soon as P0 will
leave from critical section, flag[0] = false and P1 will be able to
enter.I am little confused in this synchronisation problem, any help will be appreciated.
- Why it needs to check for the turn variable. Why not only this: while(flag[0]== true) As soon as P0 will leave from critical section, flag[0] = false and P1 will be able to enter
If you were to use just flag[0] and flag[1] it would lead to a deadlock. Let us consider P0 sets the flag[0] = true and goes ahead to check the condition in while loop. Before P0 can load the flag[1] value in a register for comparison, P1 sets flag[1] = true. So now P0 loads the value true and will keep waiting and since the flag[0] too is true and P0 is stuck in the while loop, P1 too will wait on the while loop. This is a deadlock condition since both are waiting for the other to change the flag value to false.
- What will happen in the case: P1 is executing its while loop and when P0 just tries to enter the critical section and executed the line flag[0] = true . Due to some reason, it couldnt't execute the next line and terminated. In this, flag[0] is also true and turn is also 0. P1 unnecessarily waits while no process is inside the critical section.
For this question I don't think P0 terminating abruptly proves the implementation of the Peterson's solution for synchronization to be wrong. It is flaw in the program and any buggy code could lead to such a deadlock condition.