开发者

Strange behavior with G++ CAS

Consider this code:

#include <iostream>
using namespace std;

int main()
{
   bool lock = false;
   lock = __sync_val_compare_and_swap( &lock, false, true );
   cout << lock << endl;
}

I expect the result to be displayed as 1 but the开发者_C百科 o/p is 0. Just calling __sync_val_compare_and_swap( &lock, false, true ); (so the return value is not captured) and then displaying lock results in 1 being displayed.

What am I missing here?


From the GCC doco:

bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...) type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)

These builtins perform an atomic compare and swap. That is, if the current value of *ptr is oldval, then write newval into *ptr.

The “bool” version returns true if the comparison is successful and newval was written. The “val” version returns the contents of *ptr before the operation.

Seems to me that 0 is the right value. I think you are incorrectly assigning "...the contents of *ptr before the operation" to lock.

This should output sensible results:

#include <iostream>
using namespace std;

int main()
{
   bool lock = false;
   bool oldvalue = __sync_val_compare_and_swap( &lock, false, true );
   cout << lock << ", " << oldvalue << endl;
}


You are using your lock variable as both an argument to __sync_val_compare_and_swap (a pointer to lock is passed) and a recipient for the return value of __sync_val_compare_and_swap. This doesn't seem to make much sense. Which value are you interested in? The one returned through the first argument? Or the one returned as the return value of __sync_val_compare_and_swap? Decide which one you need an act accordingly.

Right now it looks that the return value of __sync_val_compare_and_swap is stored in lock last. That value should be 0, according to the specification of __sync_val_compare_and_swap. That's the value you are seeing in your experiment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜