Reputation: 6409
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.
Upvotes: 8
Views: 2544
Reputation: 34608
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;
}
Upvotes: 1
Reputation: 2454
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.
Upvotes: 3