Ome*_*mer 10 c++ padding memory-alignment
是否有一个属性可以在变量后强制填充?
我有一个易失性(非缓存)变量声明如下:
volatile int foo __attribute__((aligned(CACHE_LINE_SIZE));
Run Code Online (Sandbox Code Playgroud)
我想防止其他变量分配到同一缓存行,以避免一致性问题。我可以在 foo 之后添加一个填充变量,或者将其设置__attribute__((aligned(CACHE_LINE_SIZE))为同一编译单元中的以下变量。但是我想知道是否有更干净的方法来执行此操作,例如向变量foo本身添加属性以强制填充。
这篇博客文章介绍了一些选项:将数据与缓存行对齐。
我建议使用 C++ 11alignas:
最简单的版本
using my_padded_type = struct alignas(CACHE_LINE_SIZE) { int value;} ;
Run Code Online (Sandbox Code Playgroud)
填充位会自动添加。您可以通过检查来验证sizeof(my_padded_type)。请参阅下面的详细信息。
其他选项:
alignas(CACHE_LINE_SIZE) int foo1, foo2;
alignas(CACHE_LINE_SIZE) union { int value; char size[CACHE_LINE_SIZE]; } foo;
std::cout << "&foo1: " << &foo1 << '\t'
<< "&foo2: " << &foo2 << '\n';
// &foo1: 0x7ffd833ebe00 &foo2: 0x7ffd833ebe40
Run Code Online (Sandbox Code Playgroud)
或者
struct alignas(CACHE_LINE_SIZE) my_padded_type {
int foo; // size: 4
char p; // do not need to specify length here. this line can be omitted entirely
// auto padding so that sizeof(my_padded_type) == CACHE_LINE_SIZE
};
my_padding_type foo;
std::cout<< sizeof(my_padding_type) <<"\n"; // equals CACHE_LINE_SIZE
Run Code Online (Sandbox Code Playgroud)
填充是由编译器自动完成的,请参阅此处的示例。