Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use one variable - turn only in Peterson's solution?

Here is the Peterson's solution presented in our lecture:

//P0:

do {
  flag[0] = TRUE; turn = 1;
  while(flag[1] && turn == 1);

  //Critical section
  flag[0] = FALSE;
  //remainder section
} while(1)


//P1:

do {
  flag[1] = TRUE; turn = 0;
  while(flag[0] && turn == 0);
  
  //critical section
  flag[1] = FALSE;
  //remainder section
} while(1)

Doesn't the turn variable itself already guaranteed the requirements for critical section? Like the flag[] here seems unnecessary.

like image 993
Done Avatar asked Oct 28 '25 04:10

Done


1 Answers

The flag array specifies for each process whether it is currently interested in the critical section (i.e. whether it currently desires to enter it or is already inside it). This information is necessary for the following reason:

Assuming that process #0 desires to enter the critical section, it must know whether process #1 is currently also interested in the critical section, because process #0 must act differently depending on whether process #1 is also interested in the critical section.

If process #1 is not interested in the critical section, then process #0 should not wait for process #1 to set turn to 0, because it may wait indefinitely for this to happen, which would violate the "progress" and "bounded waiting" requirement. Instead, process #0 should simply enter the critical section in that case.

If process #1 is interested in the critical section, then process #0 should wait for process #1 to either

  • leave the critical section (which process #1 indicates by setting flag[1] to false), or
  • yield to process #0 (which process #1 indicates by setting turn to 0).

Otherwise, the "mutual exclusion" requirement would be violated.

like image 140
Andreas Wenzel Avatar answered Oct 29 '25 19:10

Andreas Wenzel