Šimon Tóth’s Post

View profile for Šimon Tóth

C++ Educational Content Creator | 20 years of Software Engineering experience distilled into digestible daily posts

While the std::shared_ptr has limited use in single-threaded code, in multi-threaded code, the notion of shared ownership (even if temporary) is fairly common. However, while multiple instances of std::shared_ptr that point to the same memory can be managed safely in multi-threaded code, operations on a single instance of a std::shared_ptr are not thread-safe. This is why C++20 introduced std::atomic<std::shared_ptr<T>> and std::atomic<std::weak_ptr<T>>, which can be used to implement thread-safe shared data structures. Unfortunately, the GCC libstdc++ implementation is not lock-free (Clang libc++ doesn't implement it), so the resulting performance can be disappointing. Compiler Explorer link: https://lnkd.in/eX89duBy #cpp #cplusplus #coding #programming #dailybiteofcpp

  • text

Doesn't shared_ptr<std::atomic<T>> hold atomic data? I don't see that it should require any new libc++/libstdc++ functionality. I guessed I missed something based on the need to add an atomic shared_ptr.

Like
Reply

I'm curious why you would say that this has limited use in single threaded code. I have lots of places where I need the lifetime of an object to extend at least as long as several other entities that use it. I can understand that also applying to different threads, but, in my experience ,it doesn't seem to be uncommon in single threaded applications.

What open source implementation would you use if you would require atomic<shared_ptr>? Facebook's folly?

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories