Hi, This is doing my head in.
I'm trying to implement some "lock-free" code and am using CAS (gcc __sync_val_compare_and_swap) to do he heavy lifting.
My problem can be shown with the following code.
volatile bool lock;
void *locktest( void *arg )
{
for ( int i = 0 ; i < 100000 ; ++i )
{
// acquire a lock
while( __sync_val_compare_and_swap( &lock, false, true ) == true )
{
// Spin while we don't acquire
}
// make sure we have the lock
assert( lock == true );
// release the lock
assert( __sync_val_compare_and_swap( &lock, true, false ) == true );
}
}
Ok, if I run the above code in 10 concurrent threads, all is well.
However, if I change the code to read
// acquire a lock
while( __sync_val_compare_and_swap( &lock, lock, true ) == true )
Notice I've changed "false" to "lock".
All hell breaks loose and the assertion
// make sure we have the lock
assert( lock == true );
Fires. Can anyone explain why this makes a difference ?
Thx Mark.