Why is the while (*lock != 0); used here? Wouldn't the code be the same if the while and if were replaced with a short circuit and such as if (*lock == 0 && test_and_set(*lock) == 0) or just two nested if statements?
This comment was marked helpful 0 times.
shabnam
@sss: Because we don't want to call test and set ( which actually modifies the memory location ) until we actually think thats the case. Till then we spin and wait to see if its worth calling test and set and only then call it.
This comment was marked helpful 0 times.
arsenal
I think a short-circuit would do the same thing there though. We're spinning anyway in the while(1), so if you keep checking on the condition if lock == 0 && test_and_set(*lock) == 0, if the lock value were set to 1 then it would short-circuit and you wouldn't actually perform the test_and_set in that case either. I'm not sure what the answer to the original query is though, except I guess it's one way of doing it.
This comment was marked helpful 0 times.
aew
I agree with @arsenal, using the if (*lock == 0 && test_and_set(*lock) == 0) condition would behave the same way, because the test_and_set will still only get called if the lock is 0.
I can't think of any scenarios where they would perform differently, I believe these are just two different ways of implementing the test_and_test_and_set lock.
Why is the while
(*lock != 0);
used here? Wouldn't the code be the same if the while and if were replaced with a short circuit and such asif (*lock == 0 && test_and_set(*lock) == 0)
or just two nested if statements?This comment was marked helpful 0 times.
@sss: Because we don't want to call test and set ( which actually modifies the memory location ) until we actually think thats the case. Till then we spin and wait to see if its worth calling test and set and only then call it.
This comment was marked helpful 0 times.
I think a short-circuit would do the same thing there though. We're spinning anyway in the
while(1)
, so if you keep checking on the conditionif lock == 0 && test_and_set(*lock) == 0
, if the lock value were set to 1 then it would short-circuit and you wouldn't actually perform thetest_and_set
in that case either. I'm not sure what the answer to the original query is though, except I guess it's one way of doing it.This comment was marked helpful 0 times.
I agree with @arsenal, using the
if (*lock == 0 && test_and_set(*lock) == 0)
condition would behave the same way, because thetest_and_set
will still only get called if the lock is 0.I can't think of any scenarios where they would perform differently, I believe these are just two different ways of implementing the
test_and_test_and_set
lock.This comment was marked helpful 0 times.
@everyone: Your understanding is correct.
This comment was marked helpful 1 times.