Can I define a structure whose objects will always be in separate cache lines

I know that you can align variables with the cache line using, for example, the ((align (64))) attribute in gcc. However, I am interested in alignment (or you could call it filling) at the time the structure is declared. So, for example, for the next structure, I want to ask the compiler to create the necessary padding so that any object of this structure is always aligned with the cache line.

typedef struct
{
 int a;
 int b;
 // I want the compiler to create a padding here for cache alignment
} my_type;
+3
source share
2 answers

Yes. I can’t remember where I got this code from. I think it could be Herb Sutter's blog:

    #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 ];
    };
+3
source

. , "ed" aligned.

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

} my_type;

56 b, .

+2

All Articles