Skip to content

add intrusive atomic ref count (CRTP)#5

Open
AneesPatel wants to merge 1 commit into
mainfrom
feat/atomic-ref-count
Open

add intrusive atomic ref count (CRTP)#5
AneesPatel wants to merge 1 commit into
mainfrom
feat/atomic-ref-count

Conversation

@AneesPatel

Copy link
Copy Markdown
Owner

What

Intrusive atomic reference count using CRTP. The building block behind shared_ptr's control block and reference-counted lock-free nodes.

Why intrusive vs shared_ptr

shared_ptr stores its reference count in a separate heap-allocated control block - two allocations and two pointer dereferences per access. An intrusive ref count lives inline in the object itself, so one allocation and one pointer. Matters when you're building chains of lock-free nodes.

The memory ordering story

add_ref uses memory_order_relaxed - fine because the caller must have already obtained a valid pointer through some synchronized path, so the happens-before is already established.

release uses memory_order_acq_rel - the release ensures our writes are flushed before we touch the count, the acquire ensures we see all previous releases before we call delete. Without acq_rel on the last decrement you can delete an object while another thread's writes to it are still in flight. This is a genuinely easy mistake to make.

Files

  • include/AtomicRefCount.h
  • tests/test_atomicrefcount.cpp - 8 threads all hold+release the same object, verify destructor called exactly once
  • CMakeLists.txt

Inline refcount in the object, no separate control block allocation.
Explains the acq_rel ordering on release() — easy to get wrong and
hard to debug if you use relaxed there. Good building block for
reference-counted lock-free nodes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant