std::shared_ptr Thread Safety
The documentation states that multiple threads can safely read and write different std::shared_ptr objects, even when they represent copies with shared ownership. However, this does not imply that modifying a shared_ptr object is inherently safe.
To clarify, the thread-safety guarantee of std::shared_ptr extends solely to the management of the control block that keeps track of shared ownership among multiple shared_ptr instances. The contents of the shared_ptr, including the object it points to, are not inherently thread-safe.
For instance, the code you mentioned may not behave as expected:
shared_ptr<myClass> global = make_shared<myClass>(); ... // In thread 1 shared_ptr<myClass> private = global; ... // In thread 2 global = make_shared<myClass>(); ...
In this scenario, it is not guaranteed that thread 1's private will maintain the original or the updated value of global. This is because modifying global's value in thread 2 is not thread-safe and can lead to undefined behavior.
To ensure the validity of shared_ptr instances accessed by multiple threads, it is necessary to employ synchronization mechanisms, such as std::mutex, to protect critical sections of code. It is important to treat the content of shared_ptr objects as non-thread-safe and safeguard concurrent access to shared resources using appropriate synchronization techniques.
The above is the detailed content of Is Modifying a `std::shared_ptr` Object Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!