gpt4 book ai didi

c++ - std::shared_ptr 线程安全解释

转载 作者:IT老高 更新时间:2023-10-28 11:56:08 30 4
gpt4 key购买 nike

我正在阅读 http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html一些线程安全问题对我来说仍然不清楚:

  1. 标准保证引用计数处理线程安全且独立于平台,对吧?
  2. 类似的问题 - 标准保证只有一个线程(持有最后一个引用)会在共享对象上调用 delete,对吗?
  3. shared_ptr 不保证存储在其中的对象的任何线程安全?

编辑:

伪代码:

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

在线程 IV 中调用 reset() 将删除在第一个线程中创建的 A 类的先前实例并用新实例替换它?而且在IV线程中调用reset()后其他线程只会看到新创建的对象?

最佳答案

正如其他人所指出的,您已经正确地了解了您最初的 3 个问题。

但编辑的结尾部分

Calling reset() in thread IV will delete previous instance of A class created in first thread and replace it with new instance? Moreover after calling reset() in IV thread other threads will see only newly created object?

不正确。只有 d 将指向新的 A(10),以及 abc 将继续指向原来的 A(1)。在下面的简短示例中可以清楚地看到这一点。

#include <memory>
#include <iostream>
using namespace std;

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

int main(int argc, char **argv)
{
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;
}

(很明显,我没有打扰任何线程:这不会影响 shared_ptr::reset() 行为。)

这段代码的输出是

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

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

关于c++ - std::shared_ptr 线程安全解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127816/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com