我知道您可以使用gcc中的 属性((align(64)))将变量与缓存行对齐。但是,我有兴趣在结构声明时对齐(或者你可以称之为填充)。例如,对于以下 struct ,我想要求编译器创建必要的填充,以便此结构的任何对象始终与缓存行对齐。
typedef struct
{
int a;
int b;
// I want the compiler to create a padding here for cache alignment
} my_type;
答案 0 :(得分:3)
是。我不记得从哪里得到这段代码。我想这可能是Herb Sutter的博客:
#define CACHE_LINE_SIZE 64 // Intel Core 2 cache line size.
template<typename T>
struct CacheLineStorage {
public:
[[ align(CACHE_LINE_SIZE) ]] T data;
private:
char pad[ CACHE_LINE_SIZE > sizeof(T)
? CACHE_LINE_SIZE - sizeof(T)
: 1 ];
};
答案 1 :(得分:2)
这很简单。您可能只是错过了aligned
中的“ed”。
typedef struct
{
int a __attribute__((aligned(64)));
int b;
} my_type;
如果您创建变量或其数组,结果结构将在b之后具有56字节填充。