跳转至

cache 与 false sharing

是什么 / 解决什么问题

C++ 低延迟程序的数据布局直接影响 cache 行为。false sharing 是最常见的“代码无锁但仍然很慢”的原因之一。

典型问题

struct Stats {
    std::atomic<uint64_t> producer_count;
    std::atomic<uint64_t> consumer_count;
};

两个线程分别更新两个字段,但字段在同一 cache line,核心之间会反复抢占 cache line 所有权。

改进

struct alignas(64) PaddedCounter {
    std::atomic<uint64_t> value;
};

struct Stats {
    PaddedCounter producer_count;
    PaddedCounter consumer_count;
};

数据布局原则

  1. 热字段放一起,冷字段拆出去。
  2. 避免热路径 pointer chasing。
  3. 固定大小数组通常比链表更 cache-friendly。
  4. 多线程写的字段分开 cache line。
  5. 结构体数组可能需要关注每个元素的对齐和大小。

观测

perf stat -e cache-references,cache-misses ./app
perf record -e cache-misses -g ./app