Skip to content
systemcoding.dev
Performance

Use std::hardware_destructive_interference_size in C++

Use C++17's std::hardware_destructive_interference_size to pad against false sharing, with the feature-test macro, the GCC warning and a safe fallback constant.

7 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the C++, AMD and Apple logos.

Padding to avoid false sharing needs a number, and every codebase that hard-codes 64 is making a guess about the hardware. C++17 added a standard name for the answer, std::hardware_destructive_interference_size, defined in the <new> header. It is the minimum offset between two objects that avoids them interfering through a shared cache line, and its companion std::hardware_constructive_interference_size is the maximum size of contiguous memory that is likely to share a line. This post shows how to use both, how to test that your toolchain has them, why GCC warns when you use the constant in a header, and what to put in the fallback. It uses g++ 13 and clang++ 17 with -std=c++17, on x86-64 Linux.

What the standard says

The constants appear in the standard under <new>, and in cppreference as the interference-size entries. Both are inline constexpr std::size_t. The destructive size is the offset to keep two independently written objects apart. The constructive size is the opposite guarantee: the largest size of a block that you can expect to fit in one line, if the block is aligned to it, so related data you want to travel together stays together.

sizes.cppcpp
#include <new>
#include <cstdio>

int main()
{
#ifdef __cpp_lib_hardware_interference_size
    std::printf("destructive:  %zu\n", std::hardware_destructive_interference_size);
    std::printf("constructive: %zu\n", std::hardware_constructive_interference_size);
#else
    std::printf("not provided by this standard library\n");
#endif
    return 0;
}
Text
destructive:  64
constructive: 64

On GCC 12 and later for x86-64, both values are 64. The values are chosen when the compiler is built or invoked, from the tuning target, and they do not read the CPU the program eventually runs on. That is the first surprise: the constant describes the -mtune target, not the machine at run time. A binary built on x86-64 and run on a CPU with 128-byte lines reads 64 and pads wrongly. GCC allows overriding them with the --param destructive-interference-size=N and --param constructive-interference-size=N options.

The macro __cpp_lib_hardware_interference_size is the feature-test macro from <version> and <new>, with the value 201703L. Always test it, because support landed late: GCC added the constants in release 12, MSVC in Visual Studio 2017 version 15.3, and libc++ lagged, providing them only in more recent releases. If the macro is not defined, the names do not exist and a use of them is a hard error.

Using the constant

The simplest use is an alignment on the type that holds a thread's hot data.

padded.cppcpp
#include <atomic>
#include <cstdint>
#include <new>

#ifdef __cpp_lib_hardware_interference_size
inline constexpr std::size_t kDestructive = std::hardware_destructive_interference_size;
#else
inline constexpr std::size_t kDestructive = 64;
#endif

struct alignas(kDestructive) Slot {
    std::atomic<std::uint64_t> value{0};
};

static_assert(sizeof(Slot) == kDestructive);
static_assert(alignof(Slot) == kDestructive);

The #ifdef falls back to 64 when the library lacks the name. Wrapping the choice in one named constant keeps the rest of the code uniform and gives you one place to change it. The two asserts check the layout the same way the earlier post on alignas did.

The constructive size is useful for the opposite aim: keep two fields that are read together inside one line.

hot_fields.cppcpp
#include <cstdint>
#include <new>

struct alignas(std::hardware_constructive_interference_size) Header {
    std::uint32_t length;
    std::uint32_t flags;
    std::uint64_t next;
};

static_assert(sizeof(Header) <= std::hardware_constructive_interference_size,
              "Header fits in one cache line");

The assertion fails to compile if someone adds fields until the header spills past a line, which is the guarantee you wanted. With the constructive size at 64 and a 16-byte struct, the alignas makes the object start on a line boundary, so it never straddles two.

The GCC warning

GCC 12 and later warn when you use the constants where they could end up in a header's ABI:

Text
warning: use of 'std::hardware_destructive_interference_size' [-Winterference-size]
note: its value can vary between compiler versions or with different '-mtune' or '-mcpu' flags
note: if this use is part of a public ABI, change it to instead use a constant variable you define

The reason is the first surprise above. The value depends on compiler flags, so a struct whose layout uses it can have a different sizeof in two translation units compiled with different -mtune values, which is an ODR violation. The warning is -Winterference-size, on by default. It fires when the constant is used in a header file included from elsewhere, and it does not fire in a .cpp file where the layout is private.

The advice in the message is the right one: do not use the standard constant in a public header's types. Define your own constant, as the fallback code above did, set from a build-system macro or a preprocessor test, so every translation unit sees one value. For internal types used only in one library or binary, use the standard name and silence the warning for that one line with #pragma GCC diagnostic ignored "-Winterference-size", accepting the risk is contained.

Choosing the fallback

A fallback of 64 suits x86-64 and most Arm server cores. It is wrong for Apple silicon, covered in an earlier post in this series, where the line is 128, and for some other designs. A defensive project picks the fallback by architecture.

cacheline.hppcpp
#pragma once
#include <cstddef>

#if defined(__aarch64__)
inline constexpr std::size_t kCacheLine = 128;   // Apple silicon, and conservative elsewhere on Arm
#elif defined(__powerpc64__)
inline constexpr std::size_t kCacheLine = 128;
#else
inline constexpr std::size_t kCacheLine = 64;
#endif

Using 128 on all Arm targets costs memory on the 64-byte Arm cores and is correct everywhere, and the Linux kernel makes a similar conservative choice for some Arm configurations. You can also take the maximum of your own constant and the standard one, when it exists, with std::max, which is constexpr in C++14 and later.

Checking what you got

Print the value your build uses, so you notice if a toolchain upgrade changes it.

report.cppcpp
#include <new>
#include <cstdio>

int main()
{
#ifdef __cpp_lib_hardware_interference_size
    std::printf("std value in use: %zu\n", std::hardware_destructive_interference_size);
#endif
    return 0;
}
Text
std value in use: 64

Compile with -Wno-interference-size for this program only if you must use it from a shared place, or keep the check in a .cpp file. Beyond printing, verify with the cache information of the machine: getconf LEVEL1_DCACHE_LINESIZE on Linux or sysctl hw.cachelinesize on macOS, covered in the cache sizes post, should agree with the constant you use. If it does not, your build target differs from your run target.

Limits to remember

The constant is a compile-time estimate, never a guarantee. It does not know about the adjacent-line prefetcher on some Intel cores, which pulls in pairs of lines, so padding to 128 on those can help even when the line is 64. It says nothing about the L2 or other levels. And it assumes the object is aligned to it, so it must be combined with alignas, not just used as a size.

A short checklist before adopting it

Four questions decide whether to use the standard constant or your own. Is the type in a public header? Then use your own constant. Do you build for several architectures from one source tree? Then set your own constant per architecture, since the standard value follows each target's tuning anyway but may not be what you want on a new one. Does your code need the layout to be identical across builds, for example because it is written to a file or shared memory? Then never derive the layout from a value that can change with compiler flags. And do you test the result? Whatever you choose, assert it with static_assert on alignof and sizeof, so a toolchain change that moves the value fails the build instead of silently moving your padding.

The constant is also a good documentation tool. Writing alignas(std::hardware_destructive_interference_size) in a private implementation file tells the next reader what the padding is for, in a way a bare 64 never does, and a grep for the name finds every place the code cares about false sharing.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.