开发者

Variable at the beginning of a cache line

I want to make a multi-thread C program with a proper variable alignemt in cache, to avoid "cache sloshing". I get cac开发者_如何转开发he-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...)


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.)


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 malloced memory, you'd always have to keep a pointer to the original memory somewhere such that you can use free on that, afterwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜