Skip to main content

memory model

· 2 min read

背景

了解内存模型

  • 编译时防止重排
"memory"
The "memory" clobber tells the compiler that the assembly code performs memory reads or writes to items other than those listed in the input and output operands (for example, accessing the memory pointed to by one of the input parameters). To ensure memory contains correct values, GCC may need to flush specific register values to memory before executing the asm. Further, the compiler does not assume that any values read from memory before an asm remain unchanged after that asm; it reloads them as needed. Using the "memory" clobber effectively forms a read/write memory barrier for the compiler.

Note that this clobber does not prevent the processor from doing speculative reads past the asm statement. To prevent that, you need processor-specific fence instructions.

false sharding

demo

#include <thread>

alignas(128) volatile int counter[1024]{};

void update(int idx) {
for (int j = 0; j < 100000000; j++) ++counter[idx];
}

static const int stride = SIZE/sizeof(counter[0]);
int main() {
std::thread t1(update, 0*stride);
std::thread t2(update, 1*stride);
std::thread t3(update, 2*stride);
std::thread t4(update, 3*stride);
t1.join();
t2.join();
t3.join();
t4.join();
}

编译

g++ -DSIZE=64 -pthread -O2 cacheline.c  && perf stat -etask-clock,context-switches,cpu-migrations,cycles -r20 ./a.out

相关阅读