Are smart pointers threadsafe?

uj
Total Points:
1,350
Status Points:
0
Brown Belt
May 8, 2008 8:45 AM PDT
Rate
 
#7

I know now that Shared_ptr is thread-safe enougth for my needs and often the best solution but sometimes one wants a more lightweight alternative and I've been using Intrusive_ptr. To make it easier to use I've stolen this class from Beyond the C++ Standard Library by B. Karlsson, If a class inherits it publicly it becomes "intrusive enabled".

class IntrusiveCount { // base class to enable derived class for use with the Boost intrusive smart pointer

public:

virtual ~IntrusiveCount(){}

friend void intrusive_ptr_add_ref(IntrusiveCount* p) {

++p->ref_count;

}

friend void intrusive_ptr_release(IntrusiveCount* p) {

if (--p->ref_count == 0) delete p;

}

protected:

IntrusiveCount() : ref_count(0) {}

IntrusiveCount& operator=(const IntrusiveCount&) {

return *this;

}

private:

IntrusiveCount(const IntrusiveCount&);

short ref_count;

};

 

The problem with the above class is that its not thread-safe so I've tried to modified it using TBB. I would appreciate if someone could have a look at it and tell me if there's something wrong with my approach.

class IntrusiveCount { // thread-safe base class to enable derived class for use with the Boost intrusive smart pointer

public:

virtual ~IntrusiveCount(){}

friend void intrusive_ptr_add_ref(IntrusiveCount* p) {

p->ref_count.fetch_and_add(1); // increment counter atomically

}

friend void intrusive_ptr_release(IntrusiveCount* p) {

if (p->ref_count.fetch_and_add(-1) == 1) delete p; // decrement counter. If it was 1 before it's 0 now so delete

}

protected:

IntrusiveCount() {ref_count=0;}

IntrusiveCount& operator=(const IntrusiveCount&) {

return *this;

}

private:

IntrusiveCount(const IntrusiveCount&);

tbb::atomic<int> ref_count;

};

 

I had to change the counter to an int (from short) otherwise I get this level 2 warning on VS2008 standard,

 

C:UsersadminDocumentsMint bbsrcinclude bbatomic.h(157) : warning C4244: 'argument' :

conversion from 'tbb::internal::atomic_traits<Size,M>::word' to 'short', possible loss of data

 



Intel Software Network Forums Statistics

8290 users have contributed to 31236 threads and 99111 posts to date.
In the past 24 hours, we have 7 new thread(s) 20 new posts(s), and 30 new user(s).

In the past 3 days, the most popular thread for everyone has been comparison cilk++, openmp, pthreads first results The most posts were made to comparison cilk++, openmp, pthreads first results The post with the most views is Very amusing...  Escalated as

Please welcome our newest member zq.x