Boost logo

Boost Users :

Subject: Re: [Boost-users] Thread safe intrusive ptr
From: Zeljko Vrba (zvrba_at_[hidden])
Date: 2009-04-04 02:09:28


On Fri, Apr 03, 2009 at 08:10:27PM -0700, dhruva wrote:
>
> I suggest using spinlock. I have not yet seen inside the boost code thoroughly, it might be sitting right there. pthread_mutex on UNIX and CRITICAL_SECTION on windows. I am trying to see if atomic operations could help here. The only problem I see is when the reference count reaches zero (0), you need to delete/free the held pointer. The checking of the reference count and freeing the resource has to be atomic and cannot be achieved using purely atomic operations.
>
Depends on the architecture. On x86, the lock dec [mem] instruction will
atomically set the zero flag if the result has reached zero. Other compilers
offer intrinsic functions that return the new or the previous value of memory.

I'm not sure than you even need an atomic test: the reference count can reach
zero iff it is currently 1. However, if it is currently 1, only one reference
to the object exists and it is owned by the current thread. Therefore, *only*
the current thread can make another copy of the pointer and cause the count
to increment.

Even code like the following would work, provided that memory visibility
matters have been taken care of by other threads when adjusting the counter:

if(cnt == 1) {
  cnt = 0;
  delete object;
} else {
  atomic_dec(&cnt);
}

By the way, there's pthread_spin_lock and pthread_spin_unlock.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net