Understanding std::shared_ptr Thread Safety
The documentation refers to the thread safety of the control block, which manages the shared ownership of the object. Multiple threads can concurrently access different shared_ptr objects, as they share ownership of the underlying resource without conflicts. However, this does not guarantee the safety of modifying the shared object itself.
Shared_ptr and Object Modifications
In your code example, thread 1 creates a private copy of global using shared_ptr, while thread 2 modifies global itself. The following explains the behavior:
Thread Safety Considerations
To safely modify an object shared by multiple threads, you must use a synchronization mechanism such as std::mutex. The following example demonstrates a thread-safe configuration update using a mutex:
// Shared pointer to the configuration object std::shared_ptr<Configuration> global_config = make_shared<Configuration>(); // Mutex to protect the configuration object std::mutex config_mutex; void thread_fcn() { // Lock the mutex before accessing the configuration std::lock_guard<std::mutex> lock(config_mutex); // Update the configuration from global_config // ... // Unlock the mutex after finishing the update }
By acquiring the mutex before modifying global_config, you prevent any interference from other threads. This ensures that the configuration is always updated in a consistent and thread-safe manner.
The above is the detailed content of Is std::shared_ptr Thread-Safe When Modifying Shared Objects?. For more information, please follow other related articles on the PHP Chinese website!