Skip to content
systemcoding.dev
Concurrency

Implement a Lock-Free Linked List with Marked Pointers

Build Harris's lock-free sorted list in C++20 with a mark bit in the next pointer: insert, delete and search, plus the memory reclamation caveat.

7 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, C++ and Rust logos.

A lock-free list has to solve a problem that a locked list never meets: two threads can each change a different pointer of the same neighborhood, and both changes are individually valid while the combination is not. Thread A deletes node b by pointing a.next at c. Thread B inserts x after b by pointing b.next at x. Both compare-and-swap operations succeed, and x is now reachable only through a node that has already been unlinked. The insert is lost. Tim Harris described the standard fix in his 2001 paper "A Pragmatic Implementation of Non-Blocking Linked-Lists": mark the victim's next pointer before unlinking it, so that nobody can insert behind a node that is dying. This post builds that list in C++20 with std::atomic, and says plainly where the textbook version stops being safe to ship.

If you have not placed the atomics layer yet, the earlier posts in this cluster cover compare-and-swap and memory ordering. Here we assume you can read compare_exchange_strong and know what acquire and release mean.

Why one CAS cannot delete a node safely

Deleting b from a -> b -> c means changing a.next from b to c. That single CAS is atomic, but it does not stop another thread from reading b.next a moment earlier and CAS-ing it to splice in x. The second CAS succeeds because b.next still held c when it looked. After both finish, the list is a -> c, and x is gone.

Harris splits deletion into two CAS steps. The first sets a mark on b.next (logical deletion). Once b.next carries the mark, any CAS that expects the unmarked value fails, so nobody can insert after b. The second CAS physically unlinks b by swinging a.next to c. Any thread that bumps into a marked node while traversing is allowed to finish the physical unlink on the deleter's behalf, which is what keeps the algorithm lock-free: a stalled deleter cannot block progress.

Packing the mark into the pointer

The mark and the pointer must change in one atomic operation, so they share one word. Nodes are allocated with at least 8-byte alignment on every mainstream 64-bit ABI, so the low bit of a node address is always zero and can carry the mark. We wrap that in three helpers:

list.cppcpp
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <climits>

struct Node {
    int key;
    std::atomic<std::uintptr_t> next;   // pointer | mark bit
    Node(int k, Node* n = nullptr)
        : key(k), next(reinterpret_cast<std::uintptr_t>(n)) {}
};

static inline bool is_marked(std::uintptr_t p) { return p & 1u; }
static inline Node* ptr(std::uintptr_t p) {
    return reinterpret_cast<Node*>(p & ~std::uintptr_t{1});
}
static inline std::uintptr_t with_mark(Node* n) {
    return reinterpret_cast<std::uintptr_t>(n) | 1u;
}
static inline std::uintptr_t plain(Node* n) {
    return reinterpret_cast<std::uintptr_t>(n);
}

Storing the next field as std::atomic<std::uintptr_t> instead of std::atomic<Node*> avoids casting an atomic pointer to an integer, which the standard does not allow. The list is sorted by key, with a head sentinel holding INT_MIN and a tail sentinel holding INT_MAX, so search never has to test for a null pointer.

The search that cleans up as it goes

Everything else is built on one function. search(key) returns a pair (left, right) where right is the first unmarked node with a key greater than or equal to key, left is its predecessor, and the two are adjacent at the moment of return. If it sees marked nodes between them, it removes them with one CAS first.

list.cppcpp
struct List {
    Node head{INT_MIN};
    Node tail{INT_MAX};

    List() { head.next.store(plain(&tail)); }

    // Returns right; sets left. left->next == right when the function returns.
    Node* search(int key, Node*& left) {
        for (;;) {
            Node* left_next = nullptr;
            Node* t = &head;
            std::uintptr_t t_next = t->next.load(std::memory_order_acquire);
            // Walk until we find an unmarked node with key >= target.
            do {
                if (!is_marked(t_next)) {
                    left = t;
                    left_next = ptr(t_next);
                }
                t = ptr(t_next);
                if (t == &tail) break;
                t_next = t->next.load(std::memory_order_acquire);
            } while (is_marked(t_next) || t->key < key);
            Node* right = t;

            if (left_next == right) {
                // Adjacent already; make sure right was not marked meanwhile.
                if (right != &tail &&
                    is_marked(right->next.load(std::memory_order_acquire)))
                    continue;
                return right;
            }
            // Snip out the run of marked nodes between left and right.
            std::uintptr_t expected = plain(left_next);
            if (left->next.compare_exchange_strong(
                    expected, plain(right),
                    std::memory_order_acq_rel, std::memory_order_acquire)) {
                if (right != &tail &&
                    is_marked(right->next.load(std::memory_order_acquire)))
                    continue;
                return right;
            }
        }
    }

The loop keeps left as the last unmarked node it has seen and left_next as that node's successor. Marked nodes in between are skipped but not yet unlinked. When the walk ends, either left_next == right and nothing needs cleaning, or a run of marked nodes sits between them and one CAS on left->next removes the whole run. If that CAS fails, someone else changed left->next, so the search restarts from the head.

Insert and delete

Insert calls search, builds the new node pointing at right, and tries to CAS left->next from right to the new node. If the CAS fails, it searches again.

list.cppcpp
    bool insert(int key) {
        Node* node = new Node(key);
        for (;;) {
            Node* left;
            Node* right = search(key, left);
            if (right != &tail && right->key == key) {
                delete node;                  // never published, safe to free
                return false;                 // duplicate
            }
            node->next.store(plain(right), std::memory_order_relaxed);
            std::uintptr_t expected = plain(right);
            if (left->next.compare_exchange_strong(
                    expected, plain(node),
                    std::memory_order_release, std::memory_order_relaxed))
                return true;
        }
    }

    bool remove(int key) {
        for (;;) {
            Node* left;
            Node* right = search(key, left);
            if (right == &tail || right->key != key) return false;
            std::uintptr_t right_next = right->next.load(std::memory_order_acquire);
            if (!is_marked(right_next)) {
                // Step 1: logical delete. Set the mark on right->next.
                if (right->next.compare_exchange_strong(
                        right_next, right_next | 1u,
                        std::memory_order_acq_rel, std::memory_order_acquire)) {
                    // Step 2: try to unlink; if it fails, search will do it.
                    std::uintptr_t expected = plain(right);
                    if (!left->next.compare_exchange_strong(
                            expected, plain(ptr(right_next)),
                            std::memory_order_acq_rel, std::memory_order_acquire)) {
                        Node* dummy;
                        search(right->key, dummy);
                    }
                    return true;
                }
            }
        }
    }

    bool contains(int key) {
        Node* left;
        Node* right = search(key, left);
        return right != &tail && right->key == key;
    }
};

The thread that wins the marking CAS is the one whose remove returns true, which is how two concurrent deleters of the same key agree on a single winner. Whether the physical unlink succeeds on the first try does not change the result; the follow-up search call finishes it.

A short single-threaded driver shows the behavior. It cannot prove the concurrent properties, but it checks that the data structure logic is right:

list.cppcpp
int main() {
    List l;
    std::printf("insert 5: %d\n", l.insert(5));
    std::printf("insert 3: %d\n", l.insert(3));
    std::printf("insert 5: %d\n", l.insert(5));
    std::printf("contains 3: %d\n", l.contains(3));
    std::printf("remove 3: %d\n", l.remove(3));
    std::printf("contains 3: %d\n", l.contains(3));
    std::printf("remove 9: %d\n", l.remove(9));
}
Text
insert 5: 1
insert 3: 1
insert 5: 0
contains 3: 1
remove 3: 1
contains 3: 0
remove 9: 0

Compile it with g++ -std=c++20 -O2 -pthread list.cpp. The second insert of 5 returns 0 because the duplicate check in insert finds the existing key.

What the memory orders are doing

Loads that walk the list use acquire so that a node's key and initial next, written before the node was published, are visible once the pointer to it is. The publishing CAS in insert uses release for the same reason. The marking CAS uses acq_rel because it both observes the old successor and publishes the mark that other threads must see. These are conservative choices; on x86-64 they compile to plain loads and lock cmpxchg, and on Arm they produce the acquire and release forms of the exclusive or compare-and-swap instructions. If you use seq_cst everywhere the algorithm still works, only with more barriers than it needs.

Where this stops being production code

The code above leaks every removed node, and that is deliberate: freeing one is the hard part. A thread inside search may hold a raw pointer to a node that another thread just unlinked. If the deleter calls delete, the reader dereferences freed memory. A recycled address also opens the ABA problem, where a CAS succeeds because the pointer value matches even though the node it pointed to is gone and was reused.

The usual remedies are hazard pointers (Michael, 2004), epoch-based reclamation, or an RCU-style grace period, each of which adds bookkeeping to every traversal. C++26 standardizes hazard pointers and RCU in the <hazard_pointer> and <rcu> headers, but compiler support lags, so check your standard library before relying on them. Until you have picked a reclamation scheme, treat this list as a model of the algorithm, not a container to deploy. Counting nodes with a leak sanitizer will show the leak, and that is expected here.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.