
JOAQUIN LOPEZ MU?Z wrote:
Hello,
A naive usage of intrusive_ptr involves having a refcount embedded in the pointed to object and providing add_red and release functions like:
void intrusive_ptr_add_ref(const my_class* p) { ++(p->ref); }
template<typename T> void intrusive_ptr_release(const my_class* p) { if(--(p->ref)==0){ // whatever } }
But, AFAICS, this is not thread safe, as intrusive_ptr itself does not add any thread safety layer. So my question is how to efficiently provide add_ref and release functions which are thread safe (wrt to refcounting)? I can use a class-level boost::detail::lightweight_mutex in the obvious way, but I understand shared_ptr uses much more advanced mechanisms and maybe these are available for (semi)public consuption at boost/detail.
An atomic counter should suffice. boost::detail::atomic_count.
Is it enough to use an atomic counter? It seems like the entire decrement *and test* operation in intrusive_ptr_release needs to be atomic. Otherwise you run the risk of the "// whatever" code being executed twice in different threads. Sorry for responding to a topic that is a little dated. I ran across this thread yesterday when I was dealing with the same issue.

On 8/1/06, Dave Compton <abcdave@fastmail.fm> wrote:
Is it enough to use an atomic counter? It seems like the entire decrement *and test* operation in intrusive_ptr_release needs to be atomic. Otherwise you run the risk of the "// whatever" code being executed twice in different threads.
Shouldn't atomic_count::operator-- return 0 in one and only one thread? If not, it wouldn't be a very good atomic counter... -- Caleb Epstein

Caleb Epstein wrote:
On 8/1/06, Dave Compton <abcdave@fastmail.fm> wrote:
Is it enough to use an atomic counter? It seems like the entire decrement *and test* operation in intrusive_ptr_release needs to be atomic. Otherwise you run the risk of the "// whatever" code being executed twice in different threads.
Shouldn't atomic_count::operator-- return 0 in one and only one thread? If not, it wouldn't be a very good atomic counter...
Yes, thank you for making that clear.
participants (2)
-
Caleb Epstein
-
Dave Compton