Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use size of in __align__ for cache alignment, while using GCC?

I have two structs.

t_struct_inner {
  int a;
  ... // a lot more members
}

t_struct_outer {
  t_struct_inner[1000] inners;
  t_struct_outer* next;
}

I malloc t_struct_outer in my code. I want t_struct_inner to be cache aligned. My solution is to use

 __attribute__((aligned(
       ((sizeof(t_struct_inner)/CACHE_LINE_SIZE)+1) * CACHE_LINE_SIZE
)))

But obviously I cannot do this as I cannot use sizeof here. I do not want to hardcode a value for aligned. Any ideas how I can achieve the above?

like image 805
sheki Avatar asked Nov 13 '22 18:11

sheki


1 Answers

Shouldn't this do the trick?

struct __attribute__((aligned(CACHE_LINE_SIZE))) t_struct_inner {
  int a;
  ... // more members.
};

Edit: Suppose your cache line is 128 bytes long and t_struct_inner's members have a total size of 259 bytes long. Due to the alignment of 128 bytes the following array:

t_struct_inner my_array[2];

is (3*128)*2 bytes long. the attribute(aligned) forces every element of the array to be aligned to an 128-byte boundary.

like image 141
Yexo Avatar answered Nov 15 '22 11:11

Yexo