Inside STL: The atomic shared_ptr -- Raymond Chen

RaymondChen_5in-150x150.jpgThe C++20 standard introduced a specialization of std::atomic for shared pointers: std::atomic<shared_ptr<T>>. How does it work?

Inside STL: The atomic shared_ptr

by Raymond Chen

From the article:

Recall that a normal shared_ptr consists of two pointers: A stored pointer that the shared_ptr returns when you call get() and a pointer to a control block which holds the strong reference count, the weak reference count, and a pointer to the managed object.

The atomic version of the shared_ptr has the same layout, with one change: The bottom two bits of the pointer to the control block are used as flags.

Exercise: Why use the control block pointer instead of the stored pointer to store the flags?

Both the glibc++ libstdc++ and msvc implementations use the bottom bit of the control block pointer as a lock bit: Before performing an operation on the atomic shared pointer, the implementation atomically sets the lock bit to indicate that an atomic operation is in progress. If anybody tries to set the lock bit and finds that it’s already set, they wait for bit to clear. When the owner of the lock bit completes the atomic operation, it clears the lock bit, allowing any waiting threads to proceed.

The difference between libstdc++ and msvc is how they wait for the lock bit to clear.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.