std :: shared_ptr线程安全解释 [英] std::shared_ptr thread safety explained

查看:184
本文介绍了std :: shared_ptr线程安全解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html and some thread safety issues are still not clear for me:


  1. 标准保证引用计数处理线程安全,

  2. 类似的问题 - 标准保证只有一个线程(持有最后一个引用)会调用共享对象上的删除操作,对吗?

  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()之后,其他线程将只看到新创建的对象?

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?

推荐答案

但是编辑的结束部分


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

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 )。这可以在以下简短示例中清楚地看到。

is incorrect. Only d will point to the new A(10), and a, b, and c will continue to point to the original A(1). This can be seen clearly in the following short example.

#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()行为。)

(Clearly, I didn't bother with any threading: that doesn't factor into the shared_ptr::reset() behavior.)

此代码的输出是


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

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

a: 1 c:1 d:10

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

这篇关于std :: shared_ptr线程安全解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆