How to force evaluation of an always false function?

4 weeks ago 18
ARTICLE AD BOX

Have some multi-threaded code that needs to do some locking. The details of that do not matter here. But I do the canonical do { ... } while (!CAS) loop.
To keep the code concise I want to add a wait in the while condition.

Obviously the wait always returns true.
In the following code (godbolt link)
As far as I can tell the wait function does not get optimized out, even though it does not affect the while condition.
Is the wait() always guaranteed to run if the CAS fails, or should I rewrite the wait() function somehow to prevent the optimizer from eliminating it?

#include <atomic> #include <thread> #include <chrono> #include <stdio.h> bool wait() { using namespace std::chrono_literals; std::this_thread::sleep_for(10ms); return true; } int main() { int* data = new(int); std::atomic_ref atomic_data(*data); atomic_data.store(1, std::memory_order_relaxed); auto expected = 2; auto fail = true; do { if (0 == expected ) { break; } fail = !atomic_data.compare_exchange_weak(expected, expected + 1, std::memory_order_release, std::memory_order_relaxed); expected = 2; //force !success, so wait must run } while ( !(fail or wait()) ); }
Read Entire Article