I have found this code for compareAndSwap
in a StackOverflow answer:
boolean CompareAndSwapPointer(volatile * void * ptr,
void * new_value,
void * old_value) {
#if defined(_MSC_VER)
if (InterlockedCompareExchange(ptr, new_value, old_value) == old_value) return false;
else return true;
#elif (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100
return __sync_bool_compare_and_swap(ptr, old_value, new_value);
#else
# error No implementation
#endif
}
Is this the most proper way of having portable fast code, (Except assembly inlining).
Also, one problem is that those specific builtin
methods have different parameters and return values from one compiler to another, which may require some additional changes like the if then else
in this example.
Also another problem would be the behavior of these builtin
methods in the machine code level, do they behave exactly the same ? (e.g use the same assembly instructions)
Note: Another problem would be if there is many supported platforms not just (Windows
and Linux
) as in this example. The code might get very big.