Can I define a struct whose objects will always be in separate cache lines
c, c++, caching, gcc, x86-64
Solution
Yes. I can't remember where I got this code from. I think it might have been 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 ];
};
Problem
I know that you can align variables to a cache line by using for example attribute((align(64))) in gcc. 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; ```