The C++11 way is more useful: If the exchange fails, then *expected
is updated to the new, current value. That makes it easy to use the function in a loop:
T value = x.load();
T newvalue = frob(value);
while (!atomic_compare_exchange(&x, &value, newvalue))
{
newvalue = frob(value);
}
With the Microsoft signature, testing whether the operation succeeded is more cumbersome, and ditto for GCC's __sync_type
version. With GCC's __sync_bool
, you even need to perform another load each time the exchange fails.