Fix False Sharing With alignas(64) and Padding
Fix false sharing in C++17 by giving each thread's data its own cache line with alignas(64), explicit padding, static_assert checks and aligned heap allocation.

You have found a false-sharing problem: threads that write different variables slow each other down because the variables share a cache line. The fix is to give each thread's hot data a line of its own. In C++ the language gives you the tool, alignas, and a few traps come with it: arrays inside structs, heap allocation that ignores the alignment, and a constant of 64 that is not right on every machine. This post fixes a counter structure step by step in C++17 with g++ 13, checks each step with static_assert and printed addresses, and covers the heap case that most posts skip. It assumes you know what false sharing is, from the earlier post in this series.
Starting point
A statistics block, one slot per worker thread, laid out as a plain array.
#include <atomic>
#include <cstdint>
struct Stats {
std::atomic<std::uint64_t> requests{0};
std::atomic<std::uint64_t> errors{0};
};
constexpr int kWorkers = 8;
Stats stats[kWorkers];sizeof(Stats) is 16 bytes, so four Stats objects fit in one 64-byte line. With eight workers, the array covers two lines, and workers 0 to 3 contend on one line while 4 to 7 contend on another. Each worker updates only its own slot, so the code is correct, and the speed is poor.
Step 1: align the struct
alignas(64) on a type raises its alignment requirement to 64, and since sizeof must be a multiple of alignof, the compiler also pads the size up to a multiple of 64. That is the whole fix for an array of objects.
#include <atomic>
#include <cstdint>
#include <cstddef>
struct alignas(64) Stats {
std::atomic<std::uint64_t> requests{0};
std::atomic<std::uint64_t> errors{0};
};
static_assert(alignof(Stats) == 64, "Stats starts on a line boundary");
static_assert(sizeof(Stats) % 64 == 0, "Stats fills whole lines");
constexpr int kWorkers = 8;
Stats stats[kWorkers];Now sizeof(Stats) is 64, and each element of the array begins on a 64-byte boundary, because the array's alignment is that of its element type. Worker i writes only stats[i], and no two workers share a line. The two static_assert lines turn an accidental change into a compile error: if someone adds a field and the struct grows past 64 bytes, sizeof becomes 128, which still passes the divisibility test, which is the intent, since it is then two lines for one worker.
Print the addresses to see it.
#include <atomic>
#include <cstdint>
#include <cstdio>
struct alignas(64) Stats {
std::atomic<std::uint64_t> requests{0};
std::atomic<std::uint64_t> errors{0};
};
Stats stats[4];
int main()
{
for (int i = 0; i < 4; i++) {
auto a = reinterpret_cast<std::uintptr_t>(&stats[i]);
std::printf("stats[%d] offset in line: %lu, line gap: %lu\n", i,
static_cast<unsigned long>(a % 64),
i ? static_cast<unsigned long>((a - reinterpret_cast<std::uintptr_t>(&stats[i - 1])) / 64) : 0ul);
}
return 0;
}stats[0] offset in line: 0, line gap: 0
stats[1] offset in line: 0, line gap: 1
stats[2] offset in line: 0, line gap: 1
stats[3] offset in line: 0, line gap: 1Every element starts at offset 0 within a line, and consecutive elements are exactly one line apart. That is the layout the hardware needs.
Step 2: pad a plain member when you cannot align the type
Sometimes you cannot change the type's alignment, perhaps because it is a library type, or because it must be tightly packed elsewhere. Wrap it, or insert padding.
#include <cstddef>
template <typename T>
struct alignas(64) CacheAligned {
T value;
};
struct Hot {
CacheAligned<long> produced; // written by the producer
CacheAligned<long> consumed; // written by the consumer
};
static_assert(offsetof(Hot, consumed) - offsetof(Hot, produced) == 64);The wrapper aligns and pads any type to a line. The static_assert with offsetof documents and enforces that the producer's and consumer's fields are exactly one line apart. With C++17, offsetof on this struct is fine because it is standard-layout.
Manual padding with a char[] array also works, and it is the portable choice for C and older C++:
struct Padded {
volatile long value;
char pad[64 - sizeof(long)];
};
static_assert(sizeof(Padded) == 64, "one line");Manual padding does not align the start of the struct. An array of Padded is 64 bytes per element, but the array itself may begin at an address that is not a multiple of 64, in which case every element straddles two lines. That is why alignas is better when you have it: it fixes the size and the starting alignment together.
Step 3: the heap does not honour alignas before C++17
alignas on a type makes the compiler place stack and static objects correctly. For heap allocation, before C++17 new ignored over-alignment and returned memory aligned only to __STDCPP_DEFAULT_NEW_ALIGNMENT__, typically 16 on x86-64. C++17 made new align-aware: new Stats[8] calls operator new(size_t, std::align_val_t) for over-aligned types, and the result is aligned properly when compiled with -std=c++17 or later.
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <memory>
struct alignas(64) Stats {
std::atomic<std::uint64_t> requests{0};
std::atomic<std::uint64_t> errors{0};
};
int main()
{
auto p = std::make_unique<Stats[]>(8);
auto a = reinterpret_cast<std::uintptr_t>(p.get());
std::printf("heap array offset in line: %lu\n", static_cast<unsigned long>(a % 64));
return 0;
}heap array offset in line: 0Under -std=c++17 and later, make_unique<Stats[]> allocates through the aligned operator new, so the offset is 0. Compile the same code with -std=c++14 and GCC will warn that the type has new-extended alignment and may place objects wrongly. If you are stuck on an older standard, or using a custom allocator, call aligned_alloc(64, bytes) from <cstdlib>, where bytes must be a multiple of 64, and construct objects with placement new. Containers such as std::vector<Stats> use std::allocator, which in C++17 also supports over-aligned types, though the guarantee applies only when the allocator is the default one.
Step 4: do not forget what else shares the line
Padding stops threads from sharing a line with each other. It does not stop an unrelated variable from sharing a line with your thread's hot data. A global defined next to the stats array may sit in the first line of the array, if the array start is not aligned, or in the last line's padding region. Aligning the array itself, as in step 1, handles the array's own start. For a struct on the stack, alignas on the variable does it:
void worker()
{
alignas(64) long local_count = 0;
for (int i = 0; i < 1000; i++) local_count++;
}The better design is to avoid sharing in the first place: accumulate in a local variable and write the result to shared memory once at the end, so the hot loop touches no shared line at all. Padding is for cases where the data genuinely lives in shared memory and is updated continuously, such as live statistics a monitoring thread reads.
Cost and limits
Each padded counter uses 64 bytes. Eight workers cost 512 bytes, which is nothing. A million objects costs 64 MB, which may not be acceptable and sometimes shows that the design needs fewer, larger objects, or that the objects should be grouped by owner thread, with each thread's objects contiguous and the groups separated by padding. Also, padding does not help if two threads write the same variable, which is true sharing and needs a different fix.
The constant 64 is correct for most x86-64 and Arm cores, but it is not universal. Apple silicon uses 128-byte lines, as a previous post in this series covers, and the next post shows the standard constant for it. A conservative project sets one named constant, not a literal, in a single header.
Reviewing a codebase for the pattern
Once you know the shape, grep for it. Look for arrays or vectors of small atomics or mutexes indexed by thread or worker id, structs holding a producer-side and a consumer-side field together, and statistics blocks updated from several threads. For each, ask which fields are written by which thread, and whether two writers' fields can land in one line. The compiler's layout is deterministic, so pahole -C Stats ./binary from the dwarves package prints the offsets and holes of a struct from the debug information, and shows at a glance whether two hot fields are less than 64 bytes apart.


