作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在阅读 http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html一些线程安全问题对我来说仍然不清楚:
编辑:
伪代码:
// 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)
,以及 a
、b
和 c
将继续指向原来的 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/
我是一名优秀的程序员,十分优秀!