What is false sharing, and how can you use alignas to prevent it in a multithreaded environment?
Last updated
False sharing: threads writing different variables that sit on the same cache line (typically 64 bytes) force the line to bounce between cores via cache coherency, hurting performance.
Fix: use
alignasto place each hot, independently-written variable on its own cache line, ideally withstd::hardware_destructive_interference_size(C++17) instead of hardcoding 64.Trade-off: the padding wastes memory, so apply it only to genuinely hot, concurrently-written data.