diff options
Diffstat (limited to 'common')
-rw-r--r-- | common/atomic.h | 16 | ||||
-rw-r--r-- | common/intrusive_ptr.h | 48 |
2 files changed, 56 insertions, 8 deletions
diff --git a/common/atomic.h b/common/atomic.h index e34f35bb..5e9b04c6 100644 --- a/common/atomic.h +++ b/common/atomic.h @@ -6,14 +6,14 @@ using RefCount = std::atomic<unsigned int>; -inline void InitRef(RefCount *ptr, unsigned int value) -{ ptr->store(value, std::memory_order_relaxed); } -inline unsigned int ReadRef(RefCount *ptr) -{ return ptr->load(std::memory_order_acquire); } -inline unsigned int IncrementRef(RefCount *ptr) -{ return ptr->fetch_add(1u, std::memory_order_acq_rel)+1u; } -inline unsigned int DecrementRef(RefCount *ptr) -{ return ptr->fetch_sub(1u, std::memory_order_acq_rel)-1u; } +inline void InitRef(RefCount &ref, unsigned int value) +{ ref.store(value, std::memory_order_relaxed); } +inline unsigned int ReadRef(RefCount &ref) +{ return ref.load(std::memory_order_acquire); } +inline unsigned int IncrementRef(RefCount &ref) +{ return ref.fetch_add(1u, std::memory_order_acq_rel)+1u; } +inline unsigned int DecrementRef(RefCount &ref) +{ return ref.fetch_sub(1u, std::memory_order_acq_rel)-1u; } /* WARNING: A livelock is theoretically possible if another thread keeps diff --git a/common/intrusive_ptr.h b/common/intrusive_ptr.h new file mode 100644 index 00000000..8f34aeac --- /dev/null +++ b/common/intrusive_ptr.h @@ -0,0 +1,48 @@ +#ifndef INTRUSIVE_PTR_H +#define INTRUSIVE_PTR_H + +#include "atomic.h" +#include "opthelpers.h" + + +namespace al { + +template<typename T> +class intrusive_ref { + RefCount mRef{1u}; + +public: + unsigned int add_ref() noexcept { return IncrementRef(mRef); } + unsigned int release() noexcept + { + auto ref = DecrementRef(mRef); + if(UNLIKELY(ref == 0)) + delete static_cast<T*>(this); + return ref; + } + + /** + * Release only if doing so would not bring the object to 0 references and + * delete it. Returns false if the object could not be released. + * + * NOTE: The caller is responsible for handling a failed release, as it + * means the object has no other references and needs to be be deleted + * somehow. + */ + bool releaseIfNoDelete() noexcept + { + auto val = mRef.load(std::memory_order_acquire); + while(val > 1 && !mRef.compare_exchange_strong(val, val-1, std::memory_order_acq_rel)) + { + /* val was updated with the current value on failure, so just try + * again. + */ + } + + return val >= 2; + } +}; + +} // namespace al + +#endif /* INTRUSIVE_PTR_H */ |