Aligning to cache line and knowing the cache line size

前端 未结 7 1694
盖世英雄少女心
盖世英雄少女心 2020-12-12 10:07

To prevent false sharing, I want to align each element of an array to a cache line. So first I need to know the size of a cache line, so I assign each element that amount of

相关标签:
7条回答
  • 2020-12-12 10:37

    If anyone is curious about how to do this easily in C++, I've built a library with a CacheAligned<T> class which handles determining the cache line size as well as the alignment for your T object, referenced by calling .Ref() on your CacheAligned<T> object. You can also use Aligned<typename T, size_t Alignment> if you know the cache line size beforehand, or just want to stick with the very common value of 64 (bytes).

    https://github.com/NickStrupat/Aligned

    0 讨论(0)
  • 2020-12-12 10:41

    posix_memalign or valloc can be used to align allocated memory to a cache line.

    0 讨论(0)
  • 2020-12-12 10:44

    To know the sizes, you need to look it up using the documentation for the processor, afaik there is no programatic way to do it. On the plus side however, most cache lines are of a standard size, based on intels standards. On x86 cache lines are 64 bytes, however, to prevent false sharing, you need to follow the guidelines of the processor you are targeting (intel has some special notes on its netburst based processors), generally you need to align to 64 bytes for this (intel states that you should also avoid crossing 16 byte boundries).

    To do this in C or C++ requires that you use the standard aligned_alloc function or one of the compiler specific specifiers such as __attribute__((align(64))) or __declspec(align(64)). To pad between members in a struct to split them onto different cache lines, you need on insert a member big enough to align it to the next 64 byte boundery

    0 讨论(0)
  • 2020-12-12 10:45

    Here's a table I made that has most Arm/Intel processors on it. You can use it for reference when defining constants, that way you don't have to generalize the cache line size for all architectures.

    For C++, hopefully, we will soon see hardware interface size which should be an accurate way to get this information (assuming you tell the compiler your target architecture).

    0 讨论(0)
  • 2020-12-12 10:49

    Another simple way is to just cat the /proc/cpuinfo:

    cat /proc/cpuinfo | grep cache_alignment

    0 讨论(0)
  • 2020-12-12 10:51

    I am using Linux and 8-core x86 platform. First how do I find the cache line size.

    $ getconf LEVEL1_DCACHE_LINESIZE
    64
    

    Pass the value as a macro definition to the compiler.

    $ gcc -DLEVEL1_DCACHE_LINESIZE=`getconf LEVEL1_DCACHE_LINESIZE` ...
    

    At run-time sysconf(_SC_LEVEL1_DCACHE_LINESIZE) can be used to get L1 cache size.

    0 讨论(0)
提交回复
热议问题