yyzybb537 / libgo

Go-style concurrency in C++11
MIT License
3.21k stars 757 forks source link

SharedRefObject设计思想 #162

Open bigbao9494 opened 5 years ago

bigbao9494 commented 5 years ago

1、能够给讲讲SharedRefObject,RefObjectImpl,RefObject的设计思想?实在是看不懂啊 2、注释中写到: “这里构建了一个半侵入式的引用计数体系, 使用shared_ptr语意的同时, 又可以将对象放入侵入式容器, 得到极佳的性能.” 是怎么理解的呢??求指导

struct RefObject { atomict* reference; atomict referenceImpl; Deleter deleter_;

RefObject() : referenceImpl_{1} {
    reference_ = &referenceImpl_;
}
virtual ~RefObject() {}

bool IsShared() const {
    return reference_ != &referenceImpl_;
}

void IncrementRef()
{
    ++*reference_;
}

virtual bool DecrementRef()
{
    if (--*reference_ == 0) {
        deleter_(this);
        return true;
    }
    return false;
}

long use_count() {
    return *reference_;
}

void SetDeleter(Deleter d) {
    deleter_ = d;
}

RefObject(RefObject const&) = delete;
RefObject& operator=(RefObject const&) = delete;

};

struct RefObjectImpl { atomict reference; atomict weak;

RefObjectImpl() : reference_{1}, weak_{1} {}

void IncrementWeak()
{
    ++weak_;
}

void DecrementWeak()
{
    if (--weak_ == 0) {

// printf("delete weak = %p, reference = %ld\n", this, (long)reference); delete this; } }

bool Lock()
{
    long count = reference_.load(std::memory_order_relaxed);
    do {
        if (count == 0)
            return false;
    } while (!reference_.compare_exchange_weak(count, count + 1,
                std::memory_order_acq_rel, std::memory_order_relaxed));

    return true;
}

RefObjectImpl(RefObjectImpl const&) = delete;
RefObjectImpl& operator=(RefObjectImpl const&) = delete;

};

struct SharedRefObject : public RefObject { RefObjectImpl * impl_;

SharedRefObject() : impl_(new RefObjectImpl) {
    this->reference_ = &impl_->reference_;
}

virtual bool DecrementRef()
{
    RefObjectImpl * impl = impl_;
    if (RefObject::DecrementRef()) {
        std::atomic_thread_fence(std::memory_order_acq_rel);
        impl->DecrementWeak();
        return true;
    }
    return false;
}

};

yyzybb537 commented 5 years ago

就是个侵入式智能指针啊