Search code examples
ccachingstruct

Is there a way to force structure begins at cacheline?


I have some large structure (> 64bytes), can I assure that each struct begins at a separated cacheline? Or is there some way to enforce that?


Solution

  • The C standard provides _Alignof (constant-expression) to request extra alignment. For a structure, apply it to the first element:

    struct MyTag
    {
        _Alignas(64) char x[10];
    };
    
    
    #include <stdio.h>
    
    
    int main(void)
    {
        printf("%zu\n", _Alignof (struct MyTag));  // Prints 64.
    }
    

    This requires that you have the cache line size as a compile-time constant.

    Compilers are not required to support extended alignments but will diagnose if the requested alignment is too large.

    If accepted by the compiler, this will provide the requested alignment for objects allocated by the compiler. However, malloc might return addresses without the desired alignment. For this, use struct MyTag *p = aligned_alloc(64, size);, where size is sizeof *p for one structure or N * sizeof *p for N structures.