Lock-Free Programming in C++: Understanding Hazard Pointers and std::shared_ptr as an Alternative

2025-09-17

In lock-free programming, you often have a situation where one thread is removing a node from a data structure while another thread is trying to read from it. If the first thread deletes the node's memory before the second thread is done reading, you get a dreaded use-after-free bug.

A hazard pointer is a clever solution to this problem. When a thread wants to access a node, it "publishes" a pointer to that node into a publicly accessible array of "hazard pointers." Before another thread deletes a node, it checks all the published hazard pointers. If its node is "hazardous" (meaning a hazard pointer points to it), it knows it can't delete it yet and instead puts the node on a quarantine list to be deleted later. This ensures no thread ever accesses memory that's been freed.

Since hazard_pointer isn't a standard, the "troubles" are more about its implementation and use. Here are some key points

Complexity
Implementing a correct and efficient hazard pointer scheme is notoriously difficult. It's easy to get it wrong and introduce subtle bugs.

Alternative
The std::shared_ptr is the standard and safest way to manage object lifetimes. It uses reference counting to automatically handle memory reclamation. While it might have a small performance overhead due to atomic operations, it's a much safer and simpler option for most use cases, especially if you're not building a high-performance lock-free data structure.

Scalability
A simple hazard pointer implementation can have scalability issues. Checking all hazard pointers every time can become a bottleneck if you have many threads.

Alternative
More advanced techniques like RCU (Read-Copy-Update) are used in some systems, especially in the Linux kernel. RCU is great for read-heavy workloads. It allows readers to continue using old data while a new version is being created, and the old version is only cleaned up once all readers are finished.

Third-Party Libraries
As mentioned, since it's not standard, you'd need to rely on a third-party library like TBB. This introduces a dependency on external code.

Alternative
If you want to stick to the C++ standard library, the best approach is to re-think your design to use lock-based data structures (using std::mutex and std::lock_guard) or rely on other C++ concurrency tools that are provided in the standard library. For many applications, a well-designed lock-based solution is fast enough and much easier to get right.

Here's a simplified example of how std::shared_ptr could be used as a safer alternative to a custom memory reclamation scheme in a concurrent scenario.

Let's imagine a simple concurrent list.

#include <iostream>
#include <memory> // for std::shared_ptr
#include <mutex> // for std::mutex and std::lock_guard

// A simple node for our list
struct Node {
    int data;
    std::shared_ptr<Node> next;
};

// A simple, thread-safe linked list
class ThreadSafeList {
private:
    std::shared_ptr<Node> head;
    std::mutex mtx; // Protects access to the list's head

public:
    void add(int value) {
        std::lock_guard<std::mutex> lock(mtx);
        auto newNode = std::make_shared<Node>();
        newNode->data = value;
        newNode->next = head;
        head = newNode;
    }

    // This operation is now thread-safe due to std::shared_ptr's nature
    bool find(int value) {
        std::shared_ptr<Node> current;
        {
            std::lock_guard<std::mutex> lock(mtx);
            current = head;
        } // The lock is released here, but `current` is still valid!

        while (current) {
            if (current->data == value) {
                return true;
            }
            current = current->next;
        }
        return false;
    }
};

int main() {
    ThreadSafeList list;
    list.add(10);
    list.add(20);
    std::cout << "Found 10? " << std::boolalpha << list.find(10) << std::endl;
    return 0;
}

In this example, when find retrieves the head pointer, it copies the std::shared_ptr. The lock is released immediately, but the current shared pointer keeps the Node object alive until current goes out of scope. If another thread adds or removes a node, current will still be valid. This completely eliminates the use-after-free issue without complex hazard pointers.


cpp



Avoiding Undefined Behavior with C++ std::queue::back

One of the biggest issues with std::queue::back is calling it on an empty queue. Think of it like trying to grab the last item from a totally empty shelf—there's nothing there! When you do this


Exploring C++'s std::insert_iterator::operator*

The std::insert_iterator is a special kind of iterator in C++ that's used to insert elements into a container, rather than simply overwriting them


C++ Compile-Time Assertions: Understanding static_assert and its Predecessors

One of the most common issues developers face with static_assert is using a non-constant expression as the condition. static_assert can only evaluate expressions that are known at compile time



Mastering std::in_place: A Guide to In-Place Construction in C++

std::in_place is a special tag in C++ used with certain standard library classes like std::optional, std::variant, and std::any


Custom Output in C++: Avoiding operator<< Traps with std::formatter (C++20)

Here is a friendly, detailed breakdown of the common issues and some alternative approaches with sample code.Essentially


The C++ std::default_accessor: Simplifying Data Access with std::span

std::default_accessor is a component of the C++ Containers library that acts as a simple, default way to access elements within a container


Why Your C++ Header Generator is Slowing You Down (and What to Use Instead)

When we talk about a "Standard headers generator" in C++, we usually mean a tool or mechanism that automatically creates the required header (.h or


Common Pitfalls of std::isupper with C++ Strings

The main issue with using std::isupper directly on a string is that it's designed to work with individual characters, specifically those represented by an int


The Secret Key: Using std::locale::id for C++ Localization Extension

The std::locale::id class is a private, non-copyable type that acts as a unique index or identifier for a specific type of locale facet


Allocator Control or Redundancy? Understanding the Removal of std::function::assign in C++17

The std::function::assign member function was part of the std::function class in C++ (specifically from C++11 up to C++14)