Search code examples
coperating-systemsynchronizationdeadlock

What will happen if I skip waiting[i] = false In the following snippet of code?


The code below is designed to solve critical section problem. Given that there are N processes that are modifying a common data-structure in their critical section.

These are the Data Structure Used:

boolean waiting[n];
boolean lock;

Here is the testAndSet() function that is assumed to execute atomically due to hardware support.

boolean TestAndSet(boolean *target) 
{
    boolean rv = *target;
   *target = TRUE;
    return rv;
}

// The following code ensures mutual-exclusion

do {
    waiting[i] = TRUE;
    key = TRUE;

    while (waiting[i] && key)
        key = TestAndSet(&lock);

    waiting[i] = FALSE;  //what if I skip this??

    // critical section

    j = ( i + 1) % n ;
    while((j != i) && ! waiting[j])
    {
       j = (j + 1) % n ;
    }
    if (j == i)
       lock = FALSE;
    else
       waiting[j] = FALSE;

   //remainder section

   }while (TRUE);

Solution

  • You really need to indent the line after the first while.

    The stuff below the "// critical section" will unlock the next task waiting for access, or release the lock if nobody is waiting.

    If you don't clear your waiting flag, then another task (presumably running the same code around their access to protected memory) who already had the lock will think you're still waiting and will clear your waiting flag for you to allow you to run (assuming you're sitting in the loop, checking TestAndSet, the only place your wait flag is true). And it keeps the lock flag set, since it's just passing the lock on to you effectively. But if your code has actually moved on from that point without setting the value false, then you can't get back to the TestAndSet without setting your waiting flag to True, and since lock is also left at true, then this task can't run, and other tasks aren't running because the next task in line wasn't given the go-ahead (or lock wasn't set to false), and the whole system is now gummed up.