Search code examples
c++multithreadingshared-ptrtbb

shared pointers and multithreading


I have been using the following code for quite some testing now and havent run into any problems, however I just realized that the code might be not threadsafe and lead to raceconditions.

...
std::shared_ptr<T> ptr(new T(bar));

auto foo = [=] (tbb::blocked_range<int> r) {
     std::shared_ptr<T> p(ptr); // <- Is this threadsafe?
     // ... do stuff
};

tbb::parallel_for(tbb::blocked_range<int>(0,x), foo);
...

My question is concerning the marked line, as I think during the copy construction of the shared pointer racecondititons might occur due to increasing the referencecount.

Though I could just avoid that by captureing the pointer by reference and using it directly but I am still interested in the solution.


Solution

  • No, if you compile with the options for multithreading turned on, the library should be using atomic operations or locks for the reference count of shared pointers. There are no thread safety issues with the code as you've posted it.