atomic_compare_exchange with greater-than instead of equals?

atomic, c++, c++11, compare-and-swap

Solution

As requested, here's my comment as an answer:

I, too, wish this existed, but it does not, as far as I know (certainly not for x86/x64), apart from conceptually, of course, and workarounds that (potentially) use more than a single atomic instruction (which work but are not wait-free).

Problem

C++11 has a 'compare and exchange' operation for atomic variables. The semantics are: Atomically compares the value pointed to by `obj` with the value pointed to by `expected`, and if those are equal, replaces the former with `desired` (performs read-modify-write operation). Otherwise, loads the actual value pointed to by `obj` into `*expected` (performs load operation). I want to do the same, but instead of setting `*obj` when the values are equal, I want it to be set when one is greater-than the other (assume we're talking about an ordered type). Is this supported somehow? Achievable by some hack perhaps? Note: A CAS loop will not do for me, since both the values I'm comparing might change between non-atomic operations.

Original source

Related problems