Are smart pointers threadsafe?

Raf Schietekat
Total Points:
16,585
Status Points:
16,585
Black Belt
May 5, 2008 4:14 AM PDT
Rate
 
#3 Reply to #2
The documentation could be made clearer, but shared_ptr is thread-safe with regard to its reference counter (which is all you really need), even if the shared_ptr object itself is not thread-safe.

Once you have safely copied or assigned p to p1 and p2, e.g., as automatic variables or parameters, which therefore both refer to the same object underneath (the referent), you can do whatever you like to p1 in thread 1 and whatever you like to p2 in thread 2: dereference (as long as the referent is thread-safe for those accesses), reassign, reset, make further copies, anything. If you access the identical pointer instance however, e.g., as a member variable in a shared object, you need a mutex if any of those accesses are writes, perhaps a read/write mutex; there would probably be little or no benefit in extending thread safety to shared_ptr instances, which would become bigger and slower as a result, although you could easily encapsulate a shared_ptr if you would like to do that anyway.

I just don't understand example 4 (how can p2 be used in thread A and go out of scope in thread B?), and they probably should have added some examples of simultaneous use of separate instances.

(Added) I don't think a competing smart pointer should be added to TBB: boost has intentionally limited its number of possible smart pointers as much as it could for the sake of interoperability (however tempting it might be to add more with special behaviour), which is a very good reason.



Intel Software Network Forums Statistics

8293 users have contributed to 31243 threads and 99119 posts to date.
In the past 24 hours, we have 12 new thread(s) 12 new posts(s), and 24 new user(s).

In the past 3 days, the most popular thread for everyone has been huge pages on linux? The most posts were made to Pipeline buffer between stages? The post with the most views is Another example attached (Tr

Please welcome our newest member bwillems