直接映射缓存会出现错误共享吗?

问题描述 投票:0回答:1

如果内存中的每个地址直接映射到缓存中的确定性位置,则不需要缓存一致性,因为访问共享数据的所有线程共享相同的缓存。

即。在共享数据的背景下。一个线程写入缓存并不一定意味着缓存必须刷新到内存,或者访问缓存的第二个线程必须从内存中获取。因为共享数据在缓存中已经是最新的

唯一的缺点是对缓存的访问将是顺序的,缺少并行性。这种理解正确吗?

struct SharedData {
    int a;
    int b;
    int c;
    int d;
};
void threadFunc(int &var) {
    for (int i = 0; i < 1000; ++i) {
        var++;
    }
}


int main() {
    SharedData data;

    std::thread threads[NUM_THREADS];
    threads[0] = std::thread(threadFunc, std::ref(data.a));
    threads[1] = std::thread(threadFunc, std::ref(data.b));
    threads[2] = std::thread(threadFunc, std::ref(data.c));
    threads[3] = std::thread(threadFunc, std::ref(data.d));

    for (int i = 0; i < NUM_THREADS; ++i) {
        threads[i].join();
    }
}

例如,在上面的示例中,一旦 shareData 加载到缓存中,所有 4 个线程将使用相同的缓存行,而不是 4 个单独的缓存行。

我的理解正确吗?

c++ caching cpu cpu-architecture false-sharing
1个回答
0
投票

由于缓存行大小超过可变大小,并且由于具有每核顶级缓存,因此会出现错误共享问题。

直接映射缓存是缓存关联性选项,它与通常的错误共享情况无关,如您的示例中所示

© www.soinside.com 2019 - 2024. All rights reserved.