User Agents

Web browsers and everyday web tech, explained

Cache Line Sharing Between Threads Explained

· 5 min read · Cookies and Cache

In this article
  1. Background: CPU Caches and Memory Hierarchy
  2. How Cache Line Sharing Works
  3. False Sharing: A Common Performance Problem
  4. Preventing False Sharing
  5. When Sharing Is Intentional and Beneficial
  6. Frequently Asked Questions

Two threads can share the same cache line when they access variables or data that reside within the same 64-byte block of memory managed by the CPU cache. This occurs automatically due to how memory is organized and cached, not by explicit thread coordination, and can lead to performance issues like false sharing if not managed carefully.

Background: CPU Caches and Memory Hierarchy

Modern processors use a memory hierarchy to balance speed and capacity. At the top are CPU registers, followed by multiple levels of cache (L1, L2, and sometimes L3), then main memory (RAM). Caches store frequently accessed data closer to the CPU to reduce latency. Each level is progressively larger but slower. The smallest unit of data transferred between main memory and cache is the cache line, typically 64 bytes on most modern architectures (x86-64, ARM64).

When a thread reads or writes a memory location, the entire cache line containing that address is loaded into the cache. If multiple variables are located close together in memory—within the same 64-byte span—they share a cache line. If two threads running on different CPU cores access different variables that happen to be on the same cache line, they are sharing that cache line, even if they don’t intentionally communicate.

How Cache Line Sharing Works

Cache line sharing occurs at the hardware level through the cache coherence protocol, such as MESI (Modified, Exclusive, Shared, Invalid), which ensures that all CPU cores see a consistent view of memory. When one core modifies data in a cache line, the protocol marks that line as invalid in the caches of other cores. The next time another core accesses any data in that line, it must reload the updated version from memory or another cache.

For example, consider two threads running on separate cores:

  • Thread A writes to variable counter1 at memory address 0x1000.
  • Thread B writes to variable counter2 at address 0x1004.
  • If both addresses fall within the same 64-byte block (e.g., 0x1000–0x103F), they occupy the same cache line.
  • When Thread A updates counter1, the entire cache line is marked dirty.
  • Thread B’s core must invalidate and reload the line before accessing counter2, even though counter2 wasn’t changed by Thread A.

This unnecessary synchronization is known as false sharing and degrades performance.

False Sharing: A Common Performance Problem

False sharing occurs when threads modify different variables on the same cache line, triggering repeated cache invalidations and memory traffic. This can severely limit scalability in multithreaded applications, especially on systems with many cores.

Common scenarios include:

  • Arrays of counters or statistics updated by different threads.
  • Thread-local data stored adjacently in a struct or array.
  • Padding-less data structures in high-performance computing.

Performance impact varies but can result in up to 50% or more slowdown in worst-case scenarios, depending on access frequency and core count. Tools like Intel VTune, perf, or Valgrind’s Cachegrind can detect false sharing by analyzing cache miss patterns.

Preventing False Sharing

To avoid false sharing, ensure that data accessed by different threads does not reside on the same cache line. This is typically done through memory alignment and padding.

  1. Identify variables accessed independently by different threads.
  2. Ensure each such variable is aligned to a 64-byte boundary.
  3. Add padding between variables to separate them into distinct cache lines.

In C or C++, this can be achieved using compiler-specific directives:

struct ThreadData {
    int counter;
    char padding[64 - sizeof(int)]; // Ensures next field is on new cache line
};

Alternatively, use alignas (C11/C++11):

alignas(64) int counter1;
alignas(64) int counter2;

In higher-level languages like Java, use @Contended (available in JDK 8+ under certain flags) to instruct the JVM to insert padding between fields.

When Sharing Is Intentional and Beneficial

Not all cache line sharing is harmful. In some cases, it improves performance through true sharing, where threads legitimately communicate via shared data. For example:

  • A producer thread updates a flag that a consumer thread checks.
  • Shared locks or synchronization primitives like mutexes.
  • Ring buffers or queues where one thread writes and another reads adjacent elements.

In these cases, cache line sharing enables fast coordination. The key difference from false sharing is that the shared access is intentional and necessary for correctness. The performance cost of coherence traffic is justified by the need for data consistency.

Frequently Asked Questions

What is a cache line?

A cache line is the smallest unit of memory transferred between main memory and CPU cache, typically 64 bytes. It’s the granularity at which the cache operates, meaning entire lines are loaded, stored, or invalidated—even for single-byte accesses.

Why is false sharing bad?

False sharing causes unnecessary cache coherence traffic. When one thread modifies data on a shared cache line, other cores must reload that line even if they use unrelated variables. This increases memory latency and reduces parallel performance, especially on multi-core systems.

Can cache line size vary between processors?

Yes. While 64 bytes is standard on x86-64 and ARM64, some older or embedded processors use 32-byte or 128-byte cache lines. Code relying on cache line size should query it at runtime or use portable alignment constants (e.g., std::hardware_destructive_interference_size in C++17).

How do I detect false sharing?

Use performance profiling tools that monitor cache misses, such as Intel VTune, Linux perf, or Valgrind’s Cachegrind. High L1d or L2 cache miss rates on frequently written data may indicate false sharing. Source code review for closely packed thread-private data is also effective.

Is cache line sharing the same as race conditions?

No. Cache line sharing is a hardware-level memory access pattern, while race conditions are software bugs from unsynchronized access to shared data. You can have cache line sharing without a race (if accesses are synchronized), and race conditions without cache sharing (if variables are far apart in memory).

Does aligning data to cache lines always improve performance?

No. Overuse of padding increases memory usage and can reduce cache capacity. Only apply cache line alignment to data with high-frequency, independent access by different threads. For most applications, the default memory layout is sufficient.