gpt4 book ai didi

c++ - 线程安全的 intrusive_ptr

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:49 25 4
gpt4 key购买 nike

boost::intrusive_ptr (或自制版本)最简单的样子是这样的:

template<typename T>
class intrusive_ptr {
public:
intrusive_ptr(T* ptr) : ptr_(ptr)
{
if (ptr_) {
intrusive_ptr_add_ref(ptr_);
}
}

intrusive_ptr(const intrusive_ptr& that) : ptr_(that.ptr_)
{
if (ptr_) {
intrusive_ptr_add_ref(ptr_);
}
}

~intrusive_ptr()
{
if (ptr_) {
intrusive_ptr_release(ptr_);
}
}

// ...

private:
ptr_;
};

用法:

class Foo {
public:
// ...

private:
std::size_t refcount_;

friend void intrusive_ptr_add_ref(const Foo* p)
{
++p->refcount_;
}

friend void intrusive_ptr_release(const Foo* p)
{
if (--p->refcount_ == 0) { // line 1
delete p; // line 2
}
}
};

intrusive_ptr<Foo> p(new Foo);

显然是 Foo现在实现,intrusive_ptr<Foo> s 不是线程安全的。只需更改 Foo::refcount_ 的类型至 std::atomic<std::size_t>也不够,因为当一个线程在第 1 行和第 2 行之间时,另一个线程可能会尝试增加引用计数。

所以我的问题是:是否可以制作 intrusive_ptr线程安全,理想情况下无需诉诸互斥锁等繁重的机制?

最佳答案

So my question is: Is it possible to make intrusive_ptr thread-safe, ideally without resorting to heavy mechanisms like mutexes?

是的。将计数器更改为 std::atomic 就足够了,因为如果线程 A 将计数器值减小为零,则可以保证没有其他 intrusive_ptr<> 对象指向对象 p。 (因为如果确实存在,refcount 值仍会大于零)。

所以你担心的竞争条件不会发生。 (好吧,如果某个其他线程正在取消引用指向对象 p 的原始指针,而不是持有一个 intrusive_ptr,则可能会发生这种情况,但在这种情况下,无论如何所有的赌注都会被取消,因为程序有问题)

关于c++ - 线程安全的 intrusive_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38536005/

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