简体   繁体   English

我可以定义一个结构,其对象将始终位于单独的缓存行中

[英]Can I define a struct whose objects will always be in separate cache lines

I know that you can align variables to a cache line by using for example attribute ((align(64))) in gcc. 我知道你可以通过在gcc中使用例如属性 ((align(64)))将变量对齐到缓存行。 However, I'm interested in aligning (or you could call it padding) at structure declaration time. 但是,我有兴趣在结构声明时对齐(或者你可以称之为填充)。 So for example, for the following struct I want to ask the compiler to create necessary padding so that any object of this structure is always aligned with a cache line. 因此,例如,对于以下结构,我想要求编译器创建必要的填充,以便此结构的任何对象始终与高速缓存行对齐。

typedef struct
{
 int a;
 int b;
 // I want the compiler to create a padding here for cache alignment
} my_type;

Yes. 是。 I can't remember where I got this code from. 我不记得从哪里得到这段代码。 I think it might have been Herb Sutter's blog: 我想这可能是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 ];
    };

This is straightforward. 这很简单。 You probably just missed the "ed" in aligned . 你可能只是错过了aligned的“ed”。

typedef struct
{
 int a __attribute__((aligned(64)));
 int b;

} my_type;

The resulting struct will have a 56 byte padding after b if you create variables or an array of it. 如果您创建变量或其数组,结果结构将在b之后具有56字节填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM