
I'm in the process of changing some of my shared_ptr's to intrusive_ptr's, and I'm trying to see how difficult it will be to make it thread-safe. I need intrusive_ptr's mostly due to size constraints(allocating an extremely large number of small objects), and also the ThisPtr issue. I tried to search and find any information about making them thread-safe, but what I found didn't explain the solution or the issues. What are the considerations for making intrusive_ptr thread safe? Is it as simple as a mutex-lock / atomic counter variable? Thanks, Jared

Hello, ----- Original Message ----
From: Jared Lee Richardson
What are the considerations for making intrusive_ptr thread safe? Is it as simple as a mutex-lock / atomic counter variable?
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. I am now trying to see if I really do something with only atomic operations and will post my findings. -dhruva Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/

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.
participants (3)
-
dhruva
-
Jared Lee Richardson
-
Zeljko Vrba