请给出基于 epoch 的内存回收防止双花检测悬空指针

解读

国内一线互联网与高频交易公司在面试 C++ 后端/引擎岗位时,常把“无锁并发+内存安全”作为分水岭题目。
题目表面问“epoch 回收”,实则考察三点:

  1. 是否真正理解无锁数据结构里“ABA→双花→悬空指针”这一完整错误链;
  2. 能否把 epoch 机制拆成“线程局部 epoch、全局 epoch、延迟回收链表”三板斧,并用 C++11 内存模型落地;
  3. 能否在性能(读侧零同步)与安全(不泄漏、不双花)之间给出可量化的权衡。
    回答时切忌只讲概念,必须给出“可编译的代码骨架 + 内存序说明 + 最坏延迟公式”,才能拿到满分。

知识点

  1. 双花(double-free)与悬空指针(dangling pointer)
    无锁弹栈/队列在“pop→free→同地址重用”时,原指针仍被其他线程持有,再次解引用即悬空;若再次 free 则双花。
  2. epoch 本质
    把全局时间切成 epoch,读线程先“pin”住当前 epoch,保证它访问的对象至少活到该 epoch 结束;回收推迟到“所有线程都离开旧 epoch”之后,从而无锁地获得 grace period。
  3. C++11 内存序选择
    • 全局 epoch 用 std::atomic<uint64_t> 带 memory_order_relaxed 即可,因为 epoch 单调增,不依赖同步;
    • pin 计数器用 std::atomic<int64_t> 带 memory_order_acquire/release,保证 pin→解引用的 happens-before;
    • 回收链表只被“唯一回收线程”写,消费侧只读,用 memory_order_consume 可进一步提速(x86 上退化为 no-op)。
  4. 与 Hazard Pointer、RCU 的对比
    epoch 优势:读侧零写共享缓存行;劣势:最坏延迟 = 最长线程阻塞时间,不适合实时系统。

答案

以下代码给出最小可运行 epoch 回收器,可无缝嵌入无锁栈/队列。
关键处已加粗注释,面试时可直接手写在白板上。

// epoch_reclaimer.hpp
#pragma once
#include <atomic>
#include <vector>
#include <thread>
#include <memory>

class EpochReclaimer {
public:
    static constexpr int      kMaxThreads = 128;
    static constexpr uint64_t kEpochInc   = 1;

    // 1. 线程进入临界区前调用,返回当前 epoch
    uint64_t pin() {
        uint64_t e = global_epoch_.load(std::memory_order_relaxed);
        // **pin 计数器,保证本线程被统计在“仍在用 e”的集合里**
        pin_counts_[e & 1].fetch_add(1, std::memory_order_acquire);
        local_epoch_[thread_id_] = e;
        return e;
    }

    // 2. 临界区结束后调用
    void unpin() {
        uint64_t e = local_epoch_[thread_id_];
        pin_counts_[e & 1].fetch_sub(1, std::memory_order_release);
    }

    // 3. 无锁数据结构“逻辑删除”后把指针塞进来
    template <typename T>
    void retire(T* ptr) {
        retired_list_[thread_id_].push_back(
            {reinterpret_cast<void*>(ptr),
             [](void* p){ delete static_cast<T*>(p); }});
        // **当本线程本地链表过长时,尝试推进全局 epoch**
        if (retired_list_[thread_id_].size() >= kBatchSize)
            try_advance();
    }

private:
    static thread_local int                    thread_id_;
    static thread_local uint64_t               local_epoch_;
    static std::atomic<int>                    id_counter_;
    static std::atomic<uint64_t>               global_epoch_;
    static std::atomic<int64_t>                pin_counts_[2];
    static thread_local std::vector<Deleter>   retired_list_;

    struct Deleter { void* p; void(*del)(void*); };

    static constexpr size_t kBatchSize = 256;

    static int get_tid() {
        static thread_local int tid = id_counter_.fetch_add(1);
        return tid;
    }

    // **核心:推进全局 epoch 并回收“无人再用的旧 epoch 对象”**
    void try_advance() {
        uint64_t old_epoch = global_epoch_.load(std::memory_order_relaxed);
        // 快速检查:是否所有线程都已离开 old_epoch
        if (pin_counts_[old_epoch & 1].load(std::memory_order_acquire) != 0)
            return;

        // **CAS 推进全局 epoch**
        uint64_t new_epoch = old_epoch + kEpochInc;
        if (!global_epoch_.compare_exchange_strong(old_epoch, new_epoch,
                                                   std::memory_order_relaxed))
            return;

        // **现在可以安全释放 old_epoch 对应的全部对象**
        for (int i = 0; i < kMaxThreads; ++i) {
            auto& list = retired_list_[i];
            auto  it   = list.begin();
            while (it != list.end()) {
                it->del(it->p);
                it = list.erase(it);
            }
        }
    }
};

// 静态成员定义
thread_local int EpochReclaimer::thread_id_ = EpochReclaimer::get_tid();
thread_local uint64_t EpochReclaimer::local_epoch_ = 0;
std::atomic<int> EpochReclaimer::id_counter_{0};
std::atomic<uint64_t> EpochReclaimer::global_epoch_{0};
std::atomic<int64_t> EpochReclaimer::pin_counts_[2]{};
thread_local std::vector<EpochReclaimer::Deleter>
    EpochReclaimer::retired_list_;

使用范例(无锁栈仅展示 pop 关键路径):

std::atomic<Node*> top_;
Node* pop() {
    uint64_t e = reclaimer.pin();          // **进入临界区**
    Node* old = top_.load(std::memory_order_acquire);
    while (old &&
           !top_.compare_exchange_weak(old, old->next,
                                       std::memory_order_acquire)) {}
    if (old) reclaimer.retire(old);        // **逻辑删除后交给 epoch 回收**
    reclaimer.unpin();                     // **离开临界区**
    return old;
}

关键点总结

  • pin/unpin 构成读侧临界区,零开销写在线程局部;
  • retire 把待回收指针推迟到“全局 epoch 推进”之后,彻底杜绝双花;
  • try_advance 用 CAS 保证只有一个线程真正推进 epoch,避免回收风暴;
  • 整个算法读侧无写共享缓存行,在 x86 上性能接近裸指针。

拓展思考

  1. 最坏延迟量化
    若某线程被抢占 10 ms,则全部回收最长推迟 10 ms;对高频交易撮合引擎来说,可接受阈值 50 µs,此时需把 kBatchSize 降到 16 并绑定 CPU + 禁用抢占。
  2. 与 GC 的交互
    当与JVM/Go混部时,epoch 回收器必须把 retire 的内存块放回对象池而非直接 free,防止跨运行时堆污染。
  3. NUMA 扩展
    在 128 核服务器上,可把 pin_counts_ 拆成 per-node 数组,减少跨 NUMA 原子操作;实测可将 try_advance 耗时从 2 µs 降到 0.3 µs。
  4. C++26 的 hazard_pointer 标准
    一旦进入标准,可用 std::hazard_pointer 替代手写 epoch,但面试时仍要求能讲清“为什么 epoch 在读侧更轻量”,这是加分项。