Is in the new standard C++ atomic increment operation with the check preconditions before the incremented the value, that the atomic value was less than the specified value?
Can I do it easier and faster than the following code?
int atomic_inc(std::atomic_int& val, int less_than) {
int new_val;
int old_val = val.load();
do
{
if (old_val > less_than) return old_val;
new_val = old_val + 1;
} while (!val.compare_exchange_weak(old_val, new_val));
return new_val;
}
If somebody don't know how works compare_exchange_weak: compare_exchange_weak reads val, compares with old_val, and if they are not equal then saves val to old_val. If it is equal then save new_val to val.
increment_if_zero_mod_two
etc.). – Andrisval
is changed after it is read intoold_val
this will infinite loop. – Dohaauto old= atomicint++; if (old<less_than) { . . .
. – Armenian