Thread Safety of std::shared_ptr
The statement you cited from MSDN regarding the thread safety of std::shared_ptr can be misinterpreted. It implies that while multiple threads can concurrently read and write distinct shared_ptr objects, this does not guarantee the safety of modifying the shared_ptr object itself.
TL;DR:
The thread safety of std::shared_ptr pertains only to the management of multiple pointers pointing to the same underlying object. It does not extend to the shared object's contents or concurrent writes to the shared_ptr instance.
Breakdown:
A shared_ptr internally consists of two components:
Example:
In your code snippet, global is a shared pointer to a configuration object. Thread 1 copies global into its own shared pointer, private. If Thread 2 were to subsequently modify global, private would still point to the original configuration object, as the control block is not modified. However, if Thread 2 assigns a new configuration object to global, private would remain pointing to the original object.
Thread Safety of Pointed Objects:
The ability to safely modify the pointed object through multiple threads depends on the object's implementation. In the case of your configuration class, if it allows concurrent writes without synchronization, such as adding or removing settings, the code would not be thread-safe.
Solution:
To ensure thread safety for object modifications, use synchronization mechanisms such as std::mutex to guard access to the shared_ptr object or the shared object itself.
The above is the detailed content of Is std::shared_ptr truly thread-safe, and what about concurrent modifications to the pointed object?. For more information, please follow other related articles on the PHP Chinese website!