views:

228

answers:

3

Why isn't the test in strict alternation for the first entrance for process 0 while ( turn == 0) //then enter How can process 0 enter while (turn != 0), is'nt this the same as while (turn == 1) ?

turn = 0;
//process 0 to enter
while (TRUE) {
  while (turn != 0)
    critical_region();
  turn = 1;
  noncritical_region();
}

//process 1 to enter
while (TRUE) {
  while (turn != 1)
    critical_region();
  turn = 0;
  noncritical_region();
}
+1  A: 

If you expand the code you posted with brackets, it looks like this:

turn = 0;
//process 0 to enter
while (TRUE) 
{
   while (turn != 0)
   {
      critical_region();
   }
   turn = 1;
   noncritical_region();
}

So the first time you enter the main loop, it sets turn to 1 and calls noncritical_region. The second time it calls critical_region and presumably stays there.

knight666
A: 
I suspect the correct code is:
turn = 0;
//process 0 to enter
while (TRUE) {
   while (turn != 0) critical_region();
   turn = 1;
   noncritical_region();
}

//process 1 to enter
while (TRUE) {
while (turn != 1)  critical_region();
   turn = 0;
   noncritical_region();
}
Rohith
A: 

First off, you have the code wrong. Tanenbaum's strict alternation looks like this (his example are written without a block, but I think it's easier to follow this way):

while (TRUE) {
    while (turn != 0)
    {
        /* do nothing */
    }
    critical_region();
    turn = 1;
    noncritical_region();
}

The idea of strict alternation is two fold:

  1. At any given instant in time, only one process can be executing the function critical_region()
  2. The two processes take turns running critical_region() (i.e. once process 0 runs critical_region(), it must wait for process 1 to run critical_region() before being allowed to run it again).
R Samuel Klatchko