Course contentsShow
← C#
Lesson 668 of 1,9086. Asynchronous Programming and ConcurrencyFree lesson

False Sharing Mitigation

Avoid performance degradation caused by cache line contention in multi-threaded applications.

In this lesson, you will learn how to prevent "False Sharing," a subtle performance trap that occurs when multiple CPU cores fight over the same cache line.

Understanding Cache Lines

Modern CPUs don't read memory byte-by-byte; they load data in chunks called cache lines (typically 64 bytes). When your program updates a variable, the CPU marks that entire cache line as "modified." If two threads on different cores are working on two different variables that happen to live side-by-side on the same cache line, the hardware forces the cores to synchronize constantly. This is called False Sharing—it is "false" because the threads aren't actually sharing data, but the hardware thinks they are, causing your performance to plummet.

The Mitigation Strategy: Padding

To prevent this, you need to ensure that frequently updated variables used by different threads are separated by enough memory (padding) so that they never land on the same cache line.

Consider this example where two counters might be stored close together:

public class CounterPair
{
    // The CPU may place these two fields on the same 64-byte cache line
    public long Thread1Counter; 
    public long Thread2Counter;
}

If Thread1 updates Thread1Counter and Thread2 updates Thread2Counter, the CPU will constantly bounce the cache line back and forth between cores. We fix this by adding "padding":

public class OptimizedCounterPair
{
    public long Thread1Counter;
    // Add padding to push the next field to a different cache line
    private long _p1, _p2, _p3, _p4, _p5, _p6, _p7; 
    
    public long Thread2Counter;
}

By adding these dummy fields, you guarantee that Thread1Counter and Thread2Counter occupy different cache lines, allowing each core to work in its own private memory space without interference. In production code, you can use the [StructLayout(LayoutKind.Explicit)] attribute or the [FieldOffset] attribute to precisely control these memory positions, or use System.Runtime.CompilerServices.Padding attributes if available in your version of .NET.

Key Takeaway: False sharing occurs when independent variables share a cache line; use memory padding to isolate them and keep your multi-threaded operations truly independent.