2
$\begingroup$

I was reading operating systems concurrency control topics where I came across TestAndSet() intruction. I first referred this book. But it has got very less coverage on TestAndSet and then I googled. Obviously I came across wiki page.

The wikipedia page gives two code excerpts.

The TestAndSet() function

#define LOCKED 1

int TestAndSet(int* lockPtr) 
{
   int oldValue;     
   oldValue = *lockPtr;
   *lockPtr = LOCKED;
   return oldValue;
}

Lock() built using TestAndSet()

function Lock(boolean *lock)
{
   while (test_and_set(lock) == 1);
}

I have two doubts:

  • It seems that the TestAndSet() does not actually have test, it does contain only set part and Lock() contains the set part. Is it like that?
  • Below first excerpt, wikipedia page days:

    The code also shows that TestAndSet is really two operations: an atomic read-modify-write and a test. Only the read-modify-write needs to be atomic. (This is true because delaying the value comparison itself by any amount of time will not change the result of the test, once the value to test has been obtained. Once the code writes the initial value, the result of the test has been determined, even if it has not been computed yet)

    Does that mean we can call TestAnsSet() inside Lock(), save its return value and test against that return value anytime inside Lock()?

$\endgroup$
3
$\begingroup$

You are right, TestAndSet doesn't test the value of the flag, it merely sets it, but returns the previous value, which must be tested elsewhere.

The trick is that as the assignment is atomic, only one process can cause a transition from 0 to 1 (others only cause a "transition" from 1 to 1), and only it can pass the while.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.