繁体   English   中英

C++ 是否提供线程安全的引用计数器?

[英]Does C++ offer a thread-safe reference counter?

标准 C++ 库中是否有线程安全的引用计数器 class(或作为 Visual Studio 中的扩展),或者我是否需要从头开始编写这种 object?

我希望 object 像shared_ptr那样纯粹执行引用计数,除了它跨多个线程准确地执行此操作,并且不管理任何内容。 shared_ptr和它的表亲结构很好,因为它们定义了你需要的所有复制构造函数和赋值运算符,它们......对我来说是 C++ 中最容易出错的部分; C++ 建设者之于 C++ 开球之于美式足球。

struct Fun {

    // this member behaves in a way I appreciate, save for 2 short-comings:
    // - needless allocation event (minor)
    // - ref counting is only estimate if shared across threads (major)
    std::shared_ptr<int> smartPtr {new int};  

    // this is the hypothetical object that I'm searching for
    // + allocates only a control block for the ref count
    // + refCount.unique() respects reality when refs exist across many threads
    //   I can always count on this being the last reference
    std::object_of_desire refCount;

    // no explicit copy constructors or assignment operators necessary
    // + both members of this class provide this paperwork for me, 
    //   so I can careless toss this Fun object around and it'll move
    //   as one would expect, making only shallow copies/moves and ref counting
    Fun(); 

    ~Fun(){
        if(refCount.unique()){
             smart_assert("I swear refCount truly is unique, on pain of death");
        }
    }
}

关于线程安全的警告 w.r.t。 std::shared_ptr

  • 如果你有多个线程可以访问同一个指针object,那么如果其中一个线程修改了指针,你就会发生数据竞争。 如果每个线程都有自己的实例,指向同一个共享 state,则共享 state 上没有数据竞争。
  • 线程上指向 object 的最终修改不会发生在另一个线程观察到use_count为 1 之前。如果没有任何内容修改指向 object,则指向 object 上没有数据竞争。

这是您想要的类型

class ref_count {
public:
    bool unique() const { return ptr.use_count() == 1; }
private:
    struct empty {};
    std::shared_ptr<empty> ptr = std::make_shared<empty>();
};

暂无
暂无

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

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