- What is the cache line?
- What does false sharing mean?
- How to avoid false sharing?
Each location in the cache has a tag that contains the index of the datum
in main memory that has been cached. In a CPU’s data cache these entries are
called cache lines or cache blocks.
public static string
GetCacheBlockSize()
{
ManagementObjectSearcher
searcher = new
ManagementObjectSearcher(@”SELECT * FROM Win32_CacheMemory”);
foreach
(ManagementObject wmi in searcher.Get())
{
try
{
return
“Cache Block Size: ” +
wmi.GetPropertyValue(“BlockSize”).ToString();
}
catch
{ }
}
return
“Cache Block Size: Unknown”;
}
Sample 1:
class Data
{
public int _field1;
public int _field2;
}
private const int
_numIterations = 100000000;
private static long
_threadCounter = 2;
private static long
_startTimestamp = 0;
public static void Main()
{
Data
data = new Data();
_startTimestamp = Stopwatch.GetTimestamp();
ThreadPool.QueueUserWorkItem(o
=> PerformTest(data, 0));
ThreadPool.QueueUserWorkItem(o
=> PerformTest(data, 1));
Console.ReadKey();
}
private static void
PerformTest(Data data, byte numThread)
{
for (int i = 0; i < _numIterations; i++)
{
if
(numThread == 0)
data._field1++;
else
data._field2++;
}
if (Interlocked.Decrement(ref
_threadCounter) == 0)
Console.WriteLine(“It takes about {0} ms”, Stopwatch.GetTimestamp() – _startTimestamp);
}
Output
1: 3470119 ms
Sample 2:
[StructLayout(LayoutKind.Explicit)]
class Data
{
[FieldOffset(0)]
public int _field1;
[FieldOffset(64)]
public int _field2;
}
Output
2: 1649438 ms