synchronizationoperating-systemtest-and-set

How to use TestAndSet() for solving the critical section problem?


I'm studying for an exam and I'm having difficulty with a concept. This is the pseudo code I am given:

int mutex = 0;
do {
  while (TestAndSet(&mutex));
  // critical section
  mutiex = 0;
  // remainder section
} while (TRUE);

My instructor says that only two of the three necessary conditions (mutual exclusion, progress, and bounded waiting) are met with this code, but I don't understand which one isn't being met...??

How should the code be modified to support the missing condition to solve the critical region problem? Thanks in advance for any insight!


Solution

  • If anybody sees this looking for the answer, the above code does not support bounded waiting (there must be a bound on the amount of time a process has to wait). This is the correct code to ensure all three conditions are met to ensure synchronyzation using SetAndTest:

    do{
      waiting[i] = TRUE;
      key = TRUE;
      while(waiting[i] && key)
        key = TestAndSet(&lock);
      waiting[i] = FALSE;
    
      // 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);