Table of Contents

Hazard pointer

Hazard pointer is a memory reclamation mechanism for lock-free structures where a thread publishes pointers it's about to dereference into well-known slots. Other threads scan these slots before freeing nodes, ensuring safe deferred-free. It trades per-read overhead (publish, verify, clear) for prompt memory reclamation once no thread's slots reference a node.

Compared to RCU, hazard pointers make reads slightly more expensive but reclaim memory much faster and more finely-grained.

Example

This example shows hazard pointer slot publication pattern.

#include <stdio.h>
#include <stdatomic.h>
#include <string.h>
 
#define MAX_THREADS 16
 
struct node { int value; struct node* next; };
atomic_intptr_t hazard[MAX_THREADS];
 
struct node* safe_dereference(atomic_intptr_t* ptr, int slot) {
    struct node* p;
    do {
        p = (struct node*)atomic_load(ptr);
        atomic_store(&hazard[slot], (intptr_t)p);
    } while (p != (struct node*)atomic_load(ptr));
    return p;
}
 
int can_retire(struct node* p) {
    for (int i = 0; i < MAX_THREADS; i++) {
        if (atomic_load(&hazard[i]) == (intptr_t)p) return 0;
    }
    return 1;
}
 
int main() {
    printf("Hazard pointers enable safe concurrent memory reclamation\n");
    return 0;
}