Search code examples
c++multithreadingc++11smart-pointerslock-free

Are C++ smart pointers lockfree?


Are the following operations lockfree for std::unique_ptr and/or std::shared_ptr?

  1. Dereferencing, i.e. read(*myPtr) or myPtr->getSomething()
  2. Removing a reference, i.e. with std::move(myUniquePtr) or when a std::shared_ptr goes out of scope.

In my case, I am not concurrently accessing these pointers from multiple threads. I'm just curious if I can use them exclusively on a high-priority, lockfree thread. The objects managed by the pointers were allocated by the main thread prior to the high-priority callbacks and will not be deallocated until the callbacks cease.

Thanks!


Solution

  • All that the standard says is that for shared_ptr<> (20.7.2.2/4 "Class template shared_ptr"):

    Changes in use_count() do not reflect modifications that can introduce data races

    It doesn't say that those changes in use_count() have to be lock free. The standard permits a mutex to be used to prevent the data race.

    unique_ptr<> has no promises to prevent data races (it's not intended to be thread safe on it's own).