Is std::shared_ptr Thread-Safe When Modifying Shared Objects?
Nov 09, 2024 pm 10:55 PMUnderstanding 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 1's private is initially set to the original value of global.
- When thread 2 modifies global, it does not affect private's pointer, as private points to a different control block.
- However, private will eventually be destructed, decrementing the reference count in the control block that was modified by thread 2.
- While private will remain a valid shared_ptr, its lifetime is independent of the modified global.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

What are the definitions and calling rules of c language functions and what are the

C language function format letter case conversion steps

Where is the return value of the c language function stored in memory?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?

How does the C Standard Template Library (STL) work?
