首页  >  文章  >  后端开发  >  `std::shared_ptr` 实际上提供了多少线程安全性?

`std::shared_ptr` 实际上提供了多少线程安全性?

DDD
DDD原创
2024-11-14 17:24:02143浏览

How Much Thread-Safety Does `std::shared_ptr` Actually Provide?

To What Degree Does std::shared_ptr Ensure Thread-Safety?

Understanding the thread safety of std::shared_ptr is crucial for concurrent programming. Here's a detailed examination of your questions:

1. Standard guarantees that reference counting is handled thread safe and it's platform independent, right?

Yes, this is correct. The reference count is managed atomically, ensuring thread-safe operation regardless of the underlying platform.

2. Similar issue - standard guarantees that only one thread (holding last reference) will call delete on shared object, right?

Yes, this is also true. The standard ensures that when the last reference to a shared object is released, only one thread will call the destructor, ensuring object destruction without race conditions.

3. Shared_ptr doesn't guarantee any thread safety for the object stored in it?

Correct. std::shared_ptr provides thread safety for managing pointers and reference counts, but it does not guarantee the thread safety of the underlying object itself. The object's thread safety depends on its implementation.

Example:

Consider the following pseudo-code:

// 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));

Contrary to your assumption, after calling reset() in thread IV, d will point to the newly created A(10), while a, b, and c will continue to point to the original A(1). This behavior is illustrated in the following code:

#include <memory>
#include <iostream>

struct A {
  int a;
  A(int a) : a(a) {}
};

int main() {
  shared_ptr<A> a(new A(1));
  shared_ptr<A> b(a), c(a), d(a);

  cout << "a: " << a->a << "\tb: " << b->a
     << "\tc: " << c->a << "\td: " << d->a << endl;

  d.reset(new A(10));

  cout << "a: " << a->a << "\tb: " << b->a
     << "\tc: " << c->a << "\td: " << d->a << endl;

  return 0;
}

Output:

a: 1    b: 1    c: 1    d: 1
a: 1    b: 1    c: 1    d: 10

以上是`std::shared_ptr` 实际上提供了多少线程安全性?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn