gpt4 book ai didi

c++ - shared_ptr 的删除器是否进行任何同步?

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:55 25 4
gpt4 key购买 nike

使用多线程环境的每个人都知道您必须在线程之间进行同步以避免出现竞争情况。我对 shared_ptr 删除器中发生的同步特别感兴趣。

在我的真实情况下,我有多个类以某种方式进行交互,其中一些知道同步正在进行,而其他则不知道。对于这个例子,我人为地将它们全部捆绑到一个对象上来阐明问题:

class TestObject
{
public:
TestObject()
: mMarked(false)
{ }

~TestObject()
{
// use of mMarked here indicates that the destructor must be synchronized
// with any thread that calls mark()
std::cout << "Object " << (mMarked ? "was marked." : "was not marked.");
}

void mark() { mMarked = true; }

void someBehaviorThatDoesntNeedSynchronization();

private:
bool mMarked;
};


thread 1:
std::shared_ptr<TestObject> objPtr1 = /* initialize to some instance */;
objPtr1->someBehaviorThatDoesntNeedSynchronization();
objPtr1.reset(); // may call the destructor

thread 2:
std::shared_ptr<TestObject> objPtr2 = /* initialize to the same instance */;
objPtr2->mark();
objPtr2.reset(); // may call the destructor

规范似乎表明根本没有同步。然而,这似乎很不周到。似乎线程 1 应该知道对象发生的所有同步,然后它才能有调用析构函数的特权(如果在堆栈展开期间调用析构函数,这可能是残酷的)。

我错过了什么吗?我知道 shared_ptr 的每个实现实际上都出于这个原因进行了同步,但我在规范中找不到任何表明我可以信任它的东西。

规范中是否有任何内容表明同步将在调用删除器之前发生?

最佳答案

来自reference :

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.

关于c++ - shared_ptr 的删除器是否进行任何同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811856/

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