Skip to content

add hazard pointers for safe memory reclamation#4

Open
AneesPatel wants to merge 1 commit into
mainfrom
feat/hazard-pointers
Open

add hazard pointers for safe memory reclamation#4
AneesPatel wants to merge 1 commit into
mainfrom
feat/hazard-pointers

Conversation

@AneesPatel

Copy link
Copy Markdown
Owner

What

Hazard pointer implementation for deferred memory reclamation. Fixes the use-after-free problem that's lurking in the Treiber stack (PR #1).

The problem

In a lock-free pop: thread A reads head, gets preempted. Thread B pops the same node and deletes it. Thread A resumes and dereferences a freed pointer. Bad.

The fix

Before dereferencing any pointer that might be concurrently freed, publish it in a per-thread hazard slot. When retiring a node, scan all published hazard pointers first - only free it if nobody has it published.

Notes

  • Global hazard table: MAX_THREADS=16, one slot per thread (thread-local, acquired on first use).
  • Retire list is scanned lazily every BATCH_SIZE=32 retirements - not on every pop.
  • Test pairs hazard pointers with a SafeStack variant, verifies correct pop count across 4 prod + 4 cons threads.
  • This is the simplest version that actually works. Production code would use dynamic slot counts and smarter scan heuristics.

Files

  • include/HazardPointers.h
  • tests/test_hazardpointers.cpp
  • CMakeLists.txt

Fixes the ABA / use-after-free problem in the Treiber stack.
Threads publish what they're reading before dereferencing, scan
on retire to only free things nobody is currently protecting.
Simple version: one slot per thread, fixed max thread count.
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