在使用GCC时如何使用__align__中的大小进行缓存对齐?

she*_*eki 5 c c++ gcc g++ memory-alignment

我有两个结构.

t_struct_inner {
  int a;
  ... // a lot more members
}

t_struct_outer {
  t_struct_inner[1000] inners;
  t_struct_outer* next;
}
Run Code Online (Sandbox Code Playgroud)

t_struct_outer在我的代码中使用malloc .我希望t_struct_inner缓存对齐.我的解决方案是使用

 __attribute__((aligned(
       ((sizeof(t_struct_inner)/CACHE_LINE_SIZE)+1) * CACHE_LINE_SIZE
)))
Run Code Online (Sandbox Code Playgroud)

但显然我不能这样做,因为我不能sizeof在这里使用.我不想硬编码值aligned.我有什么想法可以实现上述目标?

Yex*_*exo 1

难道这不应该起作用吗?

struct __attribute__((aligned(CACHE_LINE_SIZE))) t_struct_inner {
  int a;
  ... // more members.
};
Run Code Online (Sandbox Code Playgroud)

编辑:假设您的缓存行长为 128 字节,t_struct_inner 的成员的总大小为 259 字节长。由于128字节对齐,以下数组:

t_struct_inner my_array[2];
Run Code Online (Sandbox Code Playgroud)

长度为 (3*128)*2 字节。属性(aligned) 强制数组的每个元素与 128 字节边界对齐。