Boost provides a sample atomically reference counted shared pointer
Here is the relevant code snippet and the explanation for the various orderings used:
Consider two threads, each holding one reference to the object, which are the last two references:
------------------------------------------------------------
Thread 1 Thread 2
------------------------------------------------------------
// play with x here
fetch_sub(...)
fetch_sub(...)
// nothing
delete x;
You have to ensure that any changes made to the object by Thread 1 in //play with x here
is visible to Thread 2 when it calls delete x;
. For this you need an acquire fence, which, together with the memory_order_release
on the fetch_sub()
calls, guarantees that the changes made by Thread 1 will be visible.