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 andLock()
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()
insideLock()
, save its return value and test against that return value anytime insideLock()
?