Home > Backend Development > C++ > body text

Is std::shared_ptr Thread-Safe When Modifying Shared Objects?

Patricia Arquette
Release: 2024-11-09 22:55:02
Original
205 people have browsed it

Is std::shared_ptr Thread-Safe When Modifying Shared Objects?

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 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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!