Home > Backend Development > C++ > Is Modifying a `std::shared_ptr` Object Thread-Safe?

Is Modifying a `std::shared_ptr` Object Thread-Safe?

Patricia Arquette
Release: 2024-11-19 17:52:03
Original
954 people have browsed it

Is Modifying a `std::shared_ptr` Object Thread-Safe?

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>();
...
Copy after login

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!

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