Home > Backend Development > C++ > Is std::shared_ptr thread-safe for the object it manages?

Is std::shared_ptr thread-safe for the object it manages?

Patricia Arquette
Release: 2024-11-15 13:03:02
Original
332 people have browsed it

Is std::shared_ptr thread-safe for the object it manages?

To what degree does std::shared_ptr ensure thread-safety?

Original Questions:

  1. Reference counting in std::shared_ptr is guaranteed to be thread-safe and platform-independent.
  2. Only the thread holding the last reference will call delete on the shared object.
  3. std::shared_ptr does not provide any thread safety for the object it stores.

Answers:

Yes, the first two questions are accurate. std::shared_ptr's reference counting and destructor invocation are thread-safe.

The third question is also correct. std::shared_ptr does not guarantee thread safety for the object stored within it. The object itself may not be thread-safe, and therefore, accessing it from multiple threads without proper synchronization could lead to undefined behavior.

Example:

Consider the following piece of pseudocode:

// Thread I
shared_ptr<A> a (new A (1));

// Thread II
shared_ptr<A> b (a);

// Thread III
shared_ptr<A> c (a);

// Thread IV
shared_ptr<A> d (a);

d.reset (new A (10));
Copy after login
  • Question: Will calling reset() in Thread IV delete the previous instance of A created in Thread I and replace it with a new instance?
  • Answer: No, only d will point to the new A(10), while a, b, and c will continue to point to the original A(1).

This is because reset() doesn't affect other threads' references to the same object. d is the only shared pointer that will point to the new instance, while the other references (a, b, and c) will remain pointing to the original instance.

The above is the detailed content of Is std::shared_ptr thread-safe for the object it manages?. 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