我想测量读取另一个线程正在写入的变量的缓存一致性(MESI)成本。我提出了以下测试,但它报告读取平均只需要 2 个周期:
// NB I used Microsoft's compiler so you will need your own rdtscp()
#include <thread>
#include <cstdint>
#include <iostream>
int global;
void write(){
uint64_t counter = 0;
while (true){
global = counter;
counter++;
}
}
void read(){
uint64_t n = 100000000;
uint32_t x;
uint64_t start = __rdtscp(&x);
for (int i = 0; i < n; i++){
volatile int copy = global + i;
}
uint64_t finish = __rdtscp(&x);
std::cout << (finish - start) / n << " cycles per read" << std::endl;
}
int main(){
std::thread thread1(write);
std::thread thread2(read);
thread1.detach();
thread2.join();
}
我的测试不正确吗?有人可以帮我改进吗?
编辑:我的理解是 MESI 与 C++ 中的原子类型无关。MESI 确保高速缓存行在多个 CPU 内核之间保持一致。因此我在这个测试中没有使用原子。
这与错误共享问题非常相似,我将有第二个全局变量,它们都占用相同的缓存行但不同的线程写入每个。由于每个变量都是由一个线程编写的,我们为什么要使用原子?