Search code examples
c++iosatomiccompare-and-swap

C++ atomic on iOS


I have the next isolated test fragment inside an iOS project:

/// ...
std::atomic_bool ab;
ab.store(true);
bool expected = false;
while (!ab.compare_exchange_weak(expected, true));
assert(0);
// ...

Provided that ab is not modified by other threads, I expected, that the loop would be infinite, but after executing I found out that the assert is failing. Why is that happening?


Solution

  • compare_exchange_weak changes the first parameter to what was actually there. So after the first iteration of the loop expected has been changed to true. This then is fed back into the loop where the compare_exchange_weak succeeds and proceeds to fail the assertion.