Are smart pointers threadsafe?

Alexey Kukanov (Intel)
Total Points:
13,396
Status Points:
13,396
Black Belt
May 9, 2008 3:10 AM PDT
Rate
 
#10 Reply to #7
uj:
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:
...//skipped when quoting

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

}

...//skipped when quoting
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

You did it almost right, except for one thing. tbb::atomic<>::fetch_and_add returns the value before the atomic addition, i.e. it is equivalent to a postfix increment, while the original code used a prefix increment.

In fact, you do not need to use fetch_and_add at all, because tbb::atomic<> overloads increment and decrement operators, in both postix and prefix forms. So the only change in the original code would be in the declaration of ref_count as tbb::atomic<int>.

By the way, which TBB package did you use? I wonder about this VS2008 warning. I believe our tests would show it; so most probably, it has been fixed in latest updates of TBB.



Intel Software Network Forums Statistics

8474 users have contributed to 31606 threads and 100656 posts to date.
In the past 24 hours, we have 30 new thread(s) 109 new posts(s), and 163 new user(s).

In the past 3 days, the most popular thread for everyone has been gemm(A,A,A) like possible? The most posts were made to gemm(A,A,A) like possible? The post with the most views is Dear Steve, excuse me for a d

Please welcome our newest member Kevin Johnson