可以shared_ptr.get()被多个线程调用,而另一个线程锁,并呼吁shared_ptr.swap()? [英] Can shared_ptr.get() be called by multiple threads while another thread locks and calls shared_ptr.swap()?

查看:462
本文介绍了可以shared_ptr.get()被多个线程调用,而另一个线程锁,并呼吁shared_ptr.swap()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是shared_ptr的安全。原谅我的伪code:

I would like to know if this is safe with shared_ptr. Pardon my pseudo code:

Thread 1:
do lock
ReadOnlyObj obj = make_shared<ReadOnlyObj>();
some_shared_ptr.swap(obj);
do unlock

Thread 2-N:
//no lock
some_shared_ptr->getterOnObj();

CPP引用说

所有成员函数(包括拷贝构造和拷贝分配)可以通过的shared_ptr的不同实例的多个线程无需额外的同步,即使这些实例是拷贝并共享相同的对象的所有权被调用。如果执行访问多个线程相同shared_ptr的不同步和任何这些访问中使用的shared_ptr的非const成员函数,那么将发生数据争的原子功能shared_ptr的重载可用于prevent数据争。

All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object. If multiple threads of execution access the same shared_ptr without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur, the shared_ptr overloads of atomic functions can be used to prevent the data race.

但是,根据本 GNU文档

升压shared_ptr的(如GCC使用)设有一个巧妙的无锁的算法,以避免竞争条件,但这种依赖在处理器上支持一个原子比较并交换指令。对于其他平台也有下跌的挫折使用互斥锁。升压(因为1.35版本)包括几种不同的实现和preprocessor选择一个基于编译器,标准库,平台等对于的libstdc ++编译器和库版本的shared_ptr是固定的,这使得事情简单得多:我们有一个原子或CAS我们不这样做,见下文锁定策略的详细信息。

The Boost shared_ptr (as used in GCC) features a clever lock-free algorithm to avoid the race condition, but this relies on the processor supporting an atomic Compare-And-Swap instruction. For other platforms there are fall-backs using mutex locks. Boost (as of version 1.35) includes several different implementations and the preprocessor selects one based on the compiler, standard library, platform etc. For the version of shared_ptr in libstdc++ the compiler and library are fixed, which makes things much simpler: we have an atomic CAS or we don't, see Lock Policy below for details.

,英特尔x86_64的支持CAS。

as far as I know, intel x86_64 supports CAS.

所以,我的问题:

的shared_ptr ::互换是非常量。获取和 - >()const的是。我一定要锁定GET / - >,也给我的使用场景上面列出?

shared_ptr::swap is non-const. get and ->() are const. Do I have to lock on get/->, too, given my usage scenario listed above?

推荐答案

我想我找到了答案自己在的提振文档。

I think I found the answer myself in the boost docs.

//--- Example 3 ---

// thread A
p = p3; // reads p3, writes p

// thread B
p3.reset(); // writes p3; undefined, simultaneous read/write

我试图做的是一个并发读取和写入,这是不确定的/不是安全的。

What I'm trying to do is a simultaneous read and write, which is undefined/not safe.

这篇关于可以shared_ptr.get()被多个线程调用,而另一个线程锁,并呼吁shared_ptr.swap()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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