Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 392
mxdubois Avatar asked Apr 08 '14 03:04

mxdubois


People also ask

Are C++ smart pointers thread safe?

Yes, the control block is thread-safe; but no, the access to the resource is not thread-safe. That means, modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once. These are all guarantees a std::shared_ptr gives you.

Do smart pointers automatically delete?

Smart pointers perform automatic memory management by tracking references to the underlying object and then automatically deleting that object when the last smart pointer that refers to that object goes away.

Is smart pointers C++ 11?

Introduction of Smart PointersC++11 comes up with its own mechanism that's Smart Pointer. When the object is destroyed it frees the memory as well. So, we don't need to delete it as Smart Pointer does will handle it.

Are smart pointers on the stack or heap?

As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object. After the smart pointer is initialized, it owns the raw pointer.


1 Answers

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.
like image 66
nosid Avatar answered Sep 28 '22 01:09

nosid