MESI跨多个线程共享数据的成本

时间:2015-09-19 18:34:48

标签: c++ multithreading mesi

我想测量读取另一个线程正在写入的变量的缓存一致性(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内核之间保持一致。因此,我没有在这个测试中使用原子。

这与假共享问题非常相似,我会有第二个全局变量,它们都占用相同的缓存行但不同的线程写入每个。由于每个变量都是由一个线程编写的,为什么我们要使用原子?

0 个答案:

没有答案
相关问题