Question

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!

Was it helpful?

Solution 2

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).

OTHER TIPS

With a reasonable implementation, you can assume:

std::unique_ptr:

  • All operations on a std::unique_ptr are as lock-free as the corresponding operations on a raw pointer, because there is nothing special regarding concurrency.

std::shared_ptr:

  • All operations, that do not change the reference count, are as lock-free as the corresponding operations on a raw pointer. That includes the operations dereferencing and move construction.
  • std::move is lock-free, because it is only a cast to an rvalue-reference.
  • The destructor of a std::shared_ptr is at least as lock-free as std::atomic<std::size_t> (can be checked with the member function is_lock_free).
  • Move assignment depends on whether the std::shared_ptr on the left side has an associated managed object or not. If there is an associated managed object, it is as lock-free as the destructor. Otherwise it is as lock-free as a move constructor, because the reference count is not changed.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top