I'm implementing a pointer / weak pointer mechanism using std::atomic
s for the reference counter (like this). For converting a weak pointer to a strong one I need to atomically
Is there a way to do this using std::atomic_int
? I think it has to be possible using one of the compare_exchange
, but I can't figure it out.
Given the definition std::atomic<int> ref_count;
int previous = ref_count.load();
for (;;)
{
if (previous == 0)
break;
if (ref_count.compare_exchange_weak(previous, previous + 1))
break;
}
previous
will hold the previous value. Note that compare_exchange_weak
will update previous if it fails.
This should do it:
bool increment_if_non_zero(std::atomic<int>& i) {
int expected = i.load();
int to_be_loaded = expected;
do {
if(expected == 0) {
to_be_loaded = expected;
}
else {
to_be_loaded = expected + 1;
}
} while(!i.compare_exchange_weak(expected, to_be_loaded));
return expected;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With