Reputation: 33817
I want to make a multi-thread C program with a proper variable alignemt in cache, to avoid "cache sloshing". I get cache-line length from /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size
, so I know how to pad my arrays to occupy full cache lines.
But, how can I be sure that an array is allocated exactly at the beginning of a cache line? Or is it automatic? (If it was automatic, I would not care about the padding...)
Upvotes: 1
Views: 533
Reputation: 78903
I don't think that there is a portable standard C function that ensures this directly. A portable way to do this is to allocate slightly more memory than you need and then offset the part that you really use to the first address that fulfills your alignment requirements. This would work for heap and stack memory, equally.
The disadvantage of this is that for malloc
ed memory, you'd always have to keep a pointer to the original memory somewhere such that you can use free
on that, afterwards.
Upvotes: 0
Reputation: 272447
To allocate memory with a specific alignment, use posix_memalign
.
(I don't know whether the memory allocator is intelligent enough to allocate on cache-line boundaries automatically, though.)
Upvotes: 3