Search code examples
c++paddingmemory-alignment

Attribute to enforce padding after a variable?


Is there an attribute to enforce padding after a variable?

I have a volatile (non-cached) variable declared as such:

volatile int foo __attribute__((aligned(CACHE_LINE_SIZE));

I would like to prevent other variables from being allocated to the same cache line, to avoid coherency issues. I can add a padding variable after foo, or set the __attribute__((aligned(CACHE_LINE_SIZE)) to the following variable in the same compilation unit. However I was wondering whether there is a cleaner way to do this, such as adding an attribute to variable foo itself to enforce padding.


Solution

  • Some options are introduced in this blog article: Aligning data with cache lines.

    I would suggest to use the C++11 alignas:

    The simplest version

    using my_padded_type = struct alignas(CACHE_LINE_SIZE) { int value;} ;
    

    Padding bits are added automatically. You can verify it by checking sizeof(my_padded_type). See details below.

    Other options:

    alignas(CACHE_LINE_SIZE) int foo1, foo2;
    alignas(CACHE_LINE_SIZE) union { int value; char size[CACHE_LINE_SIZE]; } foo;
    
    std::cout  << "&foo1: " << &foo1 << '\t'
               << "&foo2: " << &foo2 << '\n';
    // &foo1: 0x7ffd833ebe00 &foo2: 0x7ffd833ebe40
    

    or

    struct alignas(CACHE_LINE_SIZE) my_padded_type {
        int foo;  //  size: 4 
        char p;   //  do not need to specify length here. this line can be omitted entirely
        // auto padding so that sizeof(my_padded_type) == CACHE_LINE_SIZE
    }; 
    my_padding_type foo;
    std::cout<< sizeof(my_padding_type) <<"\n"; // equals CACHE_LINE_SIZE
    

    The padding is done automatically by the compiler, see the example here.