缓存行对齐(需要澄清文章) [英] Cache Line Alignment (Need clarification on article)

查看:492
本文介绍了缓存行对齐(需要澄清文章)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了我认为在我的应用程序中出现的假共享问题,我已经查看了 Sutter的文章如何对齐我的数据到缓存行。他建议使用以下C ++代码:

I've recently encountered what I think is a false-sharing problem in my application, and I've looked up Sutter's article on how to align my data to cache lines. He suggests the following C++ code:

// C++ (using C++0x alignment syntax)
template<typename T>
struct cache_line_storage {
   [[ align(CACHE_LINE_SIZE) ]] T data;
   char pad[ CACHE_LINE_SIZE > sizeof(T)
        ? CACHE_LINE_SIZE - sizeof(T)
        : 1 ];
};

我可以看到当 CACHE_LINE_SIZE> sizeof(T)是true - struct cache_line_storage 刚刚占用一个完整的缓存行内存。然而,当 sizeof(T)大于单个缓存行时,我认为我们应该通过 CACHE_LINE_SIZE - T%CACHE_LINE_SIZE 字节,以便生成的结构体的大小是缓存行大小的整数倍。我的理解有什么问题?为什么填充1个字节就足够了?

I can see how this would work when CACHE_LINE_SIZE > sizeof(T) is true -- the struct cache_line_storage just ends up taking up one full cache line of memory. However, when the sizeof(T) is larger than a single cache line, I would think that we should pad the data by CACHE_LINE_SIZE - T % CACHE_LINE_SIZE bytes, so that the resulting struct has a size that is an integral multiple of the cache line size. What is wrong with my understanding? Why does padding with 1 byte suffice?

推荐答案

你不能有大小为0的数组,编译。然而,规范的当前草案版本说这种填充是不必要的;编译器必须填充到结构的对齐方式。

You can't have arrays of size 0, so 1 is required to make it compile. However, the current draft version of the spec says that such padding is unecessary; the compiler must pad up to the struct's alignment.

请注意,如果 CACHE_LINE_SIZE 小于 alignof(T)。要解决这个问题,你应该使用 [[align(CACHE_LINE_SIZE),align(T)]] ,这将确保不会选择更小的对齐。

Note also that this code is ill-formed if CACHE_LINE_SIZE is smaller than alignof(T). To fix this, you should probably use [[align(CACHE_LINE_SIZE), align(T)]], which will ensure that a smaller alignment is never picked.

这篇关于缓存行对齐(需要澄清文章)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆