简体   繁体   English

我的不同线程是否会看到更新的shared_ptr对象

[英]Does my different threads will see the updated shared_ptr object

I have multiple threads reading from multiple shared objects. 我有多个线程从多个共享对象读取。 Each of these objects contains a shared_ptr to a Point: 这些对象中的每一个都包含一个Point的shared_ptr:

struct Point
{
int x;
int y;
}

shared_ptr<Point> dataPtr=std::make_shared<Point>(Point(...init...)); // at compile time

Then I pass it to the copy constructor of my different objects 然后我将它传递给我不同对象的复制构造函数

Object1 obj1 = Object1(..., dataPtr, ...)
Object2 obj2 = Object2(... , dataPtr, ...)

At some point, I will update the underlying point by doing: 在某些时候,我将通过以下方式更新基础点:

dataPtr.get().x=newvalue;

I dont have to take into account any race scenario, readers will be put to sleep before writing the new value. 我不必考虑任何比赛场景,读者将在写入新值之前进入睡眠状态。 However, I'd like to check with you that all threads will see the newvalue after the update, that this is not a "cached and dont see update" kind of scenario. 但是,我想与您核实,所有线程都会在更新后看到newvalue,这不是“缓存且不会看到更新”的情况。

Thks THKS

yes, all threads will see the new value, from cppreference: 是的,所有线程都会从cppreference看到新值:

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. 所有成员函数(包括复制构造函数和复制赋值)都可以由shared_ptr的不同实例上的多个线程调用,而无需额外的同步,即使这些实例是副本并共享同一对象的所有权。

but you don't have to use get() to access the stored pointer, this is much better style: 但你不必使用get()来访问存储的指针,这是更好的风格:

dataPtr->x = newvalue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM