February 7, 20251 yr The 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. View the full article
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.